Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python `print` does not work in loop

I have multi loops in together and a sleep in the most inner loop. for example:

from time import sleep

for i in range(10):
    print i,
    for j in range(-5,5):
        if j > 0:
            print '.',
        else:
            print 'D',
        sleep(1)
    print ''

if you run the code, you may expected to get i value after it D sleep 1 second and another D and again sleep until to the end.

but the result is difference, it waits 10 seconds and prints the whole line of 0 D D D D D D . . . . and waiting again to printing next line.

I found the comma at the end of printing causes this problem. How can I solve it?

like image 497
Farhadix Avatar asked Aug 18 '14 17:08

Farhadix


People also ask

Why is my while loop not working in Python?

The while loop is not run because the condition is not met. After the running the for loop the value of variable i is 5, which is greater than three. To fix this you should reassign the value before running the while loop (simply add var i=1; between the for loop and the while loop).

How do you fix a loop in Python?

You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.

How to loop number in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


1 Answers

Because of existence of comma, the output buffers until a \n.

You should flush the stdout after every print or use sys.stdout.write and flush buffer.

Define your print method:

import sys

def my_print(text):
    sys.stdout.write(str(text))
    sys.stdout.flush()

and at the end of line print a \n

like image 66
Farhadix Avatar answered Oct 24 '22 02:10

Farhadix