[Tutor] dealing with user input whose value I don't know

Alan Gauld alan.gauld at btinternet.com
Fri Oct 3 01:55:44 CEST 2008

"David" <ldl08 at gmx.net> wrote

> However, I just found out that changing input() to raw_input() 
> breaks my code:
> You want to know the average of the numbers: 1,2
> Traceback (most recent call last):
>  File "avgInput.py", line 13, in <module>
>    add = add + i
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
> **** End of process output ****
> numbers = raw_input("Please type the numbers, separated by commas: 
> ")
> numbers = input("Please type the numbers, separated by commas: ") ?

What is happening is a bit more subtle than you think. I think!...

As others have pointed out input() evaluates whatever the user types
as a python expression. Now a list of numbers separated by commas
is, to python, a tuple. So your input version stores the list of 
as a list(ie. a tuple!) whereas raw_input() stores a string containing
the list of comma separated values.

The solution you have already seen - use string.split(',') to separate
the string into substrings and then convert each substring to an

As an aside:
What you have done is actually quite a user friendly solution but
I suspect most programmers would have opted to use a loop.
Have you covered loops yet? Specifically a for loop? That would
allow you to read in really long lists of numbers and calculate
the sum as you go.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list