In jupyter notebook, is it possible to print an updating value in a replacing line?

Viewed 418

I have a loop in a Jupyter notebook, and in addition to that loop, I would like to print periodically inside that loop. For example

from tqdm.notebook import tqdm
running = 0
for itt in tqdm(range(40)):
    running = running + itt
    if itt % 10 == 0:
        print(running/10)

In addition to the tqdm bar, I get

0.0
5.5
21.0
46.5

I would like each print statement to replace the previous statement though.

So by the end I should only see 46.5

In the print statement I tried combinations of using end='/r' and flush=True, but they either keep printing new lines or no lines are being printed. I also tried tqdm.write but that results in "TypeError: 'float' object is not subscriptable "

1 Answers

You can do something like this:

from tqdm.notebook import tqdm
import time
running = 0
for itt in tqdm(range(40)):
    running = running + itt
    if itt % 10 == 0:
        print("\r{}".format(running/10), end="")
        time.sleep(1)

Test

enter image description here

Related