0

I'm new to Python and using Pycharm to work with code.

I'm writing a simple program, that read string and then convert it into int.

import sys

    print ("Hello word")
    data = sys.stdin.read()
    tokens = data.split()

    for i in range(len(tokens)):
        tokens[i] = int(tokens[i])

    print (tokens[1])

enter image description here

I ran program, entered three numbers, but that's all Why, while running the program I can't see the results of print?

Daniel Chepenko
  • 2,229
  • 7
  • 30
  • 56

2 Answers2

2

It's because the program is still reading from stdin. To read only one line from stdin, you have to use stdin.readline(). If you run a debug process with a breakpoint after the line sys.stdin.read(), you'll see that the program never reaches it. Running your program in Ideone, for example, where it lets you specify stdin before running your app, stdin.read() works fine. Usually it reads until EOF (end of file). So, either use sys.stdin.readline() (built-in input() does just that), or use file input if you want to read multiple lines. You can also refer to this post for more info if you really want to use sys.stdin.read().

Community
  • 1
  • 1
illright
  • 3,991
  • 2
  • 29
  • 54
1

You have effectively blocked the program with .read(); its a lot simpler to use input(), like this:

print('Hello World')
data = input()
tokens = map(int, data.split()) # this converts to int
print(tokens[1])
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284