[Tutor] Loops

Steven D'Aprano steve at pearwood.info
Sun Apr 5 16:54:33 CEST 2015


On Sun, Apr 05, 2015 at 01:11:06PM +0200, Marcus Lütolf wrote:
> Why do I get this traceback with the infinite loop below but not with the
> definitw loop (bottom of mail)?

You forgot to show the definite loop, but the error in the infinite loop 
is explained by the error message. You should read the error message 
carefully, it will often explain the problem you are having. Further 
comments below.

> count = 0
> total = 0
> while True:
>     x = raw_input('Enter a number')
>     count = count + 1
>     total = total + x
>     print count, total, (total/count)
>  
> 
> Traceback (most recent call last):
>   File "C:\Python27\enter_a_number.py", line 6, in <module>
>     total = total + x
> TypeError: unsupported operand type(s) for +: 'int' and 'str'

The traceback shows you the line causing the error:

    total = total + x

and describes the error: you cannot add an int and a str. Try it at the 
interactive interpreter:

py> 23 + "42"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'


The `total` variable starts as an int:

    total = 0

and x is a string. Just because you print "Enter a number" doesn't mean 
that Python magically turns x into a number. You are responsible for 
turning the string into a number. Try:

    x = int(raw_input('Enter a number'))



-- 
Steve


More information about the Tutor mailing list