"David" <[EMAIL PROTECTED]> 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 numbers
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
integer.

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
http://www.freenetpages.co.uk/hp/alan.gauld

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to