问题
I am trying to write a program that reads numbers input by the user until the user types done. If the user types a non-number other than "done," I want to return an error message like "please enter a number number. When the user types "done", I want to calculate the total of the numbers, the number count and the average. I have tried to create a while loop with try and except to catch the non-numeric error other than done. That is part of the trick, a string entry is an error unless the string is "done." Here is the beginning of my code without any attempt to create a file that can be totaled, counted and maxed.
bank = 0
number = 0
while True:
try:
number = int(raw_input("Enter an integer ( such as 49 or 3 or 16) \n"))
bank = bank + number
print 'You entered--- ', number, 'Your running total is ', bank
except:
if number == 'done':
print 'Done'
else:
if number == 'done':
print 'Done'
else:
print 'Your entry was non-numberic. Please enter a number.'
bank = number + bank
When I run this and enter "done" I get the "else:" response and a new input line. I do not get the "Done" print from if number == "done"
回答1:
Answer written in python 3
The exception used is ValueError because the compiler catches this error as a result of the conversion done in line 7 so i just added the continue in line 19 to make it skip the error and go back to the start.
bank = 0
count = 0
while True:
try:
number = input('enter an integer:\n')
if number != 'done':
bank += int(number)
print('you entered -- ', number, 'your total is ', bank)
count += 1
elif number == 'done':
print('Done')
print('you entered %d numbers' % count)
print('Your total is %s' % bank)
average = bank/count
print('Your average is %.02f' % average)
break
except ValueError:
print('oops!! that was not an integer')
continue
来源:https://stackoverflow.com/questions/34569063/python-looping-with-try-and-except