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
ForceBru
  • 43,482
  • 10
  • 63
  • 98
sudip
  • 21
  • 2

3 Answers3

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().

DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • See this answer for a more detailed explanation about EOF behavior at the beginning of a new line vs other places in a line: http://stackoverflow.com/a/7373799/1427124 – DaoWen Nov 06 '16 at 18:10
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()

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • The OP specifically mentioned using Windows, in which case Ctrl+D most likely does not result in EOF. – DaoWen Nov 06 '16 at 18:07
0

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

Example Code

user_input = input("Please input a number !")
# Rest of the code
Community
  • 1
  • 1
Michael Yousrie
  • 1,132
  • 2
  • 10
  • 20