Search code examples
pythonwindowsloopsinputundefined-behavior

Can giving input too early cause glitches?


Suppose that my Python code looks like this:

While(True):
    Var = input()
    Do something

I noticed that when I run this from a Windows prompt, I can give input while the Do something is still running. For example:

  1. If I press enter during Do something, then the next time that input is asked the Var is automatically assigned empty input.
  2. If I press something else (like 1) during Do something, then the next time that input is asked I see this in my prompt. So it says 1, and I can still choose to delete it, add something to it or press enter.
  3. If can also make combinations of these. If I press 1, enter, 1, enter during Do something, then the next two loops will start automatically with Var = 1.

This seems a bit strange and potentially nonintended. Is it possible that the algorithm will behave different/strangely/undefined if I give certain inputs during Do something?

(Note that Do something uses the value of Var)


Solution

  • It is absolutely intended. It is not specific to Python, it's how terminal input works: Whatever you type in goes into a buffer, and is held there until the running program chooses to read it. Then it will be read in strict sequence -- as long as you are typing at the command line, there is no chance that some of your input could be read out of order. And the input buffer is quite large, so you have to do a lot of type-ahead before your input is lost or rejected.

    Actually there are buffers in multiple places. What you type is not even delivered to your program until you hit Enter-- that's line-buffering at the terminal interface. But I trust this has answered your question.