使用For计算一组值的程序

时间:2015-01-08 09:28:18

标签: python

我如何处理该部分而真正的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 个答案:

答案 0 :(得分:1)

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