0

I am supposed to append all the integer values from STDIN in python.

For example:

5
6
0
4
2
4
1
0
0
4

Suppose the below is the integers coming from stdin, how can append these values in a list?

My code:

result = []

try:
    while raw_input():
        a = raw_input()
        result.append(int(a))
except EOFError:
    pass

print result

Could anyone help me? Thank you

Result is only printing [6, 4, 4, 0, 4]

3
  • Could you please give an example? Commented Jan 19, 2016 at 21:44
  • 1
    You are calling raw_input twice per loop Commented Jan 19, 2016 at 21:46
  • @walpen if you write your answer, I will upvote and accept it. You're correct Commented Jan 19, 2016 at 22:03

4 Answers 4

1

The problem is that you have called raw_input() twice.

while raw_input(): # this consumes a line, checks it, but does not do anything with the results
    a = raw_input()
    result.append(int(a))

As a general note about python. Stream like objects, including files opened for reading, stdin and StringIO among others, have an iterator that iterates over there lines. So your program can be reduced to the pythonic.

import sys
result = [int(line) for line in sys.stdin]
Sign up to request clarification or add additional context in comments.

Comments

1

You are consuming every second raw_input in the while line, change this to test that 'a' is non-null. For example:

result = []

try:
    a = raw_input()
    while a:
        result.append(int(a))
        a = raw_input()
except EOFError:
    pass

print result

Comments

0

Okay my issue is resolved using fileinput module

import fileinput

for line in fileinput.input():
    print line

Comments

0

Setting the raw_input() in the while loop to a variable ('a' in your case) should fix the issue.

result = []


a = raw_input("Enter integer pls:\n> ")
try:
    while a is not '':
        result.append(int(a))
        a = raw_input("Enter another integer pls:\n> ")
except ValueError:
    pass

print result

Comments

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.