[Tutor] Loops

Alan Gauld alan.gauld at btinternet.com
Sun Apr 5 15:18:36 CEST 2015


On 05/04/15 12:11, Marcus Lütolf wrote:
> Why do I get this traceback with the infinite loop below but not with the
> definitw loop (bottom of mail)?

I don;t see anyt loops at the bottom.
But as for this one...

> count = 0
> total = 0
>
> while True:
>      x = raw_input('Enter a number')

raw_input reads a character string. You need to converrt it to a number:

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


>      count = count + 1
>      total = total + x

Without the conversion you are trying to add a string
to a number which is illegal in Python.

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

Which is what the error is telling you.


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list