I have the following code:
count = 0
def thisisapgoram():
while True:
try:
x = int(input('Input a number:'))
count = count int(x)
except NameError:
print('Try again, sunshine')
if x == 'done' or x == 'Done':
return count
thisisapgoram()
I am attempting to create a function that requests user input. If a user inputs a number, it'll keep a log of that number and keep track. If they enter a string instead of a number, it'll provide an error message via the try and except statements -- and encourage the user to try again. If the user enters 'done', the program will return the total value of all the numbers they input into the program.
I get the following error message and am not sure why. Can someone please explain as well as provide their take on a solution?
CodePudding user response:
There are multiple problems in program:
1.Better to make count a local scope variable.
2.When casting a Value error is raised not Name error
3.You are not printing the return value
4.Line where you are casting will throw error, so x='done' will never be a case.
def thisisapgoram():
count = 0
while True:
try:
x = input('Input a number:')
x=int(x)
count = int(x)
except ValueError:
x=str(x)
if x.lower() == 'done':
return count
else:
print('Try again, sunshine')
print(thisisapgoram())
CodePudding user response:
The string done
doesn't represent an integer, so of course trying to convert it to one must fail.
You could check for done
before you try to convert to an integer. Basically, your if
is in the wrong place.
Also, why are you catching NameError
? That seems weird.