使用For来计算一组值的程序

2024-09-29 17:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何处理从真实到真实的部分?我需要一个异常,告诉用户他需要输入一个数字(以防他意外键入一个字符串)或一个值>;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()

Tags: thetoinputrawmain错误beint
1条回答
网友
1楼 · 发布于 2024-09-29 17:20:01
  1. raw_input语句移到try块中
  2. 当用户输入有效的数字字符串时,使用break关键字来中断while循环
  3. 将用户值从string转换为int。如果在类型转换过程中出现任何异常,请再次询问。这将进入代码的异常部分
  4. 另外,通过if循环检查enter number是否大于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

相关问题 更多 >

    热门问题