我如何处理该部分而真正的for?我需要一个异常,告诉用户他需要输入一个数字(如果他不小心输入一个字符串)或一个值> 0.我尝试将nyear转换为int,因此会引发值错误,但这只会导致错误。
那你们怎么处理这个?
def main():
nyear = int(raw_input('Enter the years: '))
i = 0
while True:
try:
intTarget = int(nyear)
except ValueError:
print 'Value needs to be a number and needs to be greater than 0'
nyear = int(raw_input('Enter the years: '))
for year in range(nyear):
for month in range(12):
rinch = float(raw_input('How many inches of rain: '))
i += rinch
total = i
tmonths = (month + 1) * (year + 1)
ravg = total/tmonths
print total, tmonths, ravg
main()
答案 0 :(得分:1)
raw_input
语句移至try
块。break
关键字来中断while
循环。string
转换为int
。如果在类型转换期间出现任何异常,请再次询问。这将是代码的异常部分。if
循环检查输入数字是否大于0。使用 e.g。
while True:
try:
nyear = int(raw_input('Enter the years: '))
if nyear>0:
break
print 'Value needs to be a number and needs to be greater than 0.'
except ValueError:
print 'Value needs to be a number and needs to be greater than 0.'
输出:
Enter the years: w
Value needs to be a number and needs to be greater than 0.
Enter the years: -100
Value needs to be a number and needs to be greater than 0.
Enter the years: 2015