1

I have written a simple Python3 program like below:

import sys
input = sys.stdin.read()
tokens = input.split()
print (tokens)
a = int(tokens[0])
b = int(tokens[1])
if ((a + b)> 18):
    print ("Input numbers should be between 0 and 9")
else:
    print(a + b)

but while running this like below:

C:\Python_Class>python APlusB.py
3 5<- pressed enter after this

but output is not coming until I hit ctrl+C (in windows)

C:\Python_Class>python APlusB.py
3 5
['3', '5']
8
Traceback (most recent call last):
  File "APlusB.py", line 20, in <module>
    print(a + b)
KeyboardInterrupt
1
  • use the input function. Commented Nov 6, 2016 at 18:00

3 Answers 3

2

sys.stdin.read() will read until an EOF (end of file) is encountered. That's why "pressing enter" doesn't seem to do anything. You can send an EOF on Windows by typing Ctrl+Z, or on *nix systems with Ctrl+D.

(Note that you probably still need to hit Enter before hitting Ctrl+Z. I don't think the terminal treats the EOF correctly if it's not at the start of a line.)

If you just want to read input until a newline, use input() instead of sys.stdin.read().

Sign up to request clarification or add additional context in comments.

1 Comment

See this answer for a more detailed explanation about EOF behavior at the beginning of a new line vs other places in a line: stackoverflow.com/a/7373799/1427124
0

you can read user's input using input() function.

Example Code

user_input = input("Please input a number !")
# Rest of the code

Comments

0

This happens because sys.stdin.read attempts to read all the data that the standard input can provide, including new lines, spaces, tabs, whatever. It will stop reading only if the interpreter's interrupted or it hits an EndOfFile (Ctrl+D on UNIX-like systems and Ctrl+Z on Windows).

The standard function that asks for input is simply input()

1 Comment

The OP specifically mentioned using Windows, in which case Ctrl+D most likely does not result in EOF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.