使用try和except进行Python循环 [英] Python looping with try and except
问题描述
我正在尝试编写一个程序,该程序读取用户输入的数字,直到用户键入完成为止.如果用户键入的数字不是"done",那么我想返回一条错误消息,例如请输入数字.当用户键入" done"时,我要计算数字的总数,即数字我试图用try创建一个while循环,除了捕获非完成以外的非数字错误,这是窍门的一部分,除非字符串完成",否则字符串输入是错误.代码的开头,没有尝试创建可以总计,计数和最大化的文件.
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
当我运行它并输入"done"时,我得到"else:"响应和一个新的输入行.我没有从 if number == "done"
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"
推荐答案
用python 3编写的答案
使用的异常是ValueError,因为编译器由于在第7行中进行了转换而捕获了此错误,因此我只是在第19行中添加了 continue 使其跳过错误,然后重新开始.
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
这篇关于使用try和except进行Python循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!