1

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

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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 ' ' >>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.