Questions about the order of execution of print() and sys.stdin.readline()
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?
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
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!