Ask coding questions

← Back to all posts
Questions about the order of execution of print() and sys.stdin.readline()
rlaalfks (3)

In the code, I ran print() first and then sys.stdin.readline(). However, in the console window, the print() result is displayed only after the input through sys.stdin.readline() is completed. Why does this happen?

DynamicSquid (4891)

This is a great question!

The way IO works in Python is outputs are buffered. That means when you use print(), the output doesn't get displayed right away, but instead it is stored inside of a buffer. The buffer is then outputted (called a flush) when certain statements are encountered, such as input(). The reason Python doesn't flush for every print() statement is because flushing frequently takes up quite a bit of time in larger projects, so Python tries to flush the buffer as infrequently as possible.

In this case, you're using sys.stdin.readline(), but print() doesn't recognize that statement, so it doesn't flush the buffer. That's why the output isn't showing up at the correct time.

To flush the buffer before sys.stdin.readline(), you can flush it manually like this:

print('input number2: ', end='', flush=True)

Hope this helps!

OldWizard209 (1498)

woow. I have been doing Python for a long time and just got to know about this rn. @DynamicSquid

rlaalfks (3)

Thank you. I was able to solve this problem with your help. @DynamicSquid