Python Forum
Infinite loop not working - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Infinite loop not working (/thread-29093.html)



Infinite loop not working - pmp2 - Aug-18-2020

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


RE: Infinite loop not working - DPaul - Aug-18-2020

Your second python tag should look like this: [/python]
Paul


RE: Infinite loop not working - deanhystad - Aug-18-2020

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.*