Python Forum

Full Version: Infinite loop not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am trying to get this loop to work in which a user inputs several numbers and you get the total and the mean of these numbers.

The program asks the user to input a number, but when I type in 'done', which should break the loop, I get an error. Or whenever I type in anything that isn't a number.

the code is below:


[Python]

num=0
tot=0.0

while True:
sval = input ('Enter a number: ')
if sval == 'done':
break

try:
fval=float(sval)
except:
print 'Not a number, try again'
continue


num=num+1
tot=tot+fval

print(tot,num,tot/num)

[Python]


the error I get is this:


Enter a number: 56
Enter a number: 56
Enter a number: 56
Enter a number: done
Traceback (most recent call last):
File "Ex5.5.py", line 5, in <module>
sval = input ('Enter a number: ')
File "<string>", line 1, in <module>
NameError: name 'done' is not defined
Your second python tag should look like this: [/python]
Paul
The error makes me think you are using Python 2.*. Before Python 3 the input method evaluated the string. Like a combination of fval = float(input('Enter a number')). When you typed "done" it tried to evaluate this too, searching for "done" in the current namespace and not finding it.

To make your program work you need to use raw_input instead of input. You will also have a problem with the print at the bottom of the program. In Python 2.* print was not a function, no parenthesis.

You should update to Python 3.*