Shubha Rajopadhye
Shubha Rajopadhye

Reputation: 49

Python 2.7, unexpected EOF while parsing

I am a newbie to Python and I was trying my hand at the following problem: I want to add numbers entered by the user. Here is my program

add = 0  
num = input('Enter a number:')
add = add + num
while num != ' ' : 
    num = input('Next number:')
    add = add + num
    print add

I want to terminate the program when a blank is entered. So I know the problem is with line 4. What would be the correct syntax?

Thanks in advance for your help

Upvotes: 1

Views: 3878

Answers (2)

Serdalis
Serdalis

Reputation: 10489

In python 2.7 user input should be processed using raw_input

This is because input is semantically equivalent to:

eval(raw_input(prompt))

which, when given an empty string, will cause the following line of code:

eval('')

will return an EOF error while parsing, since empty is not a valid object to parse.

Since raw_string doesnt parse the string into an int you'll also have to use int() to convert it when you do the addition.
You also need to change to while statement:

add = 0  
num = raw_input('Enter a number:')
# you cant do a + here what if the user hits enter right away.
if num:
    add = int(num)

while num: # enter will result in a null string not a space
    num = raw_input('Next number:')
    if num:
        add = add + int(num)
    print add

Upvotes: 3

user1602017
user1602017

Reputation: 1169

Try following and read a bit.

>>> help(input)

>>> help(raw_input)

>>> s=raw_input()
<return right here>
>>> s
''
>>> s=raw_input()
 <one space followed by return here>
>>> s
' '
>>>

Upvotes: 0

Related Questions