使用 For 计算一组值的程序

Program that uses a For to calculate a set of values

如何处理从 while True 到 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()
  1. raw_input 语句移动到 try 块中。
  2. 当用户输入有效的数字字符串时,使用 break 关键字来中断 while 循环。
  3. 将用户值从 string 转换为 int。如果在类型转换期间出现任何异常,请再次询问。这将进入代码的异常部分。
  4. 同时通过 if 循环检查输入数字是否大于 0。

使用 例如

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