响应python中的错误

2024-09-29 23:20:26 发布

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

我是python的新手,也遇到过这个问题。这个程序的作用是询问用户的年龄。年龄必须是一个数字,否则它将返回一个值错误。我已经使用try/except方法来响应错误,但是我也希望它能够让用户输入的年龄低于一个特定的值(例如200)。你知道吗

while True:
    try:
        age=int(input('Please enter your age in years'))
        break
    except ValueError:
        print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
    except:
        if age>=200:
            print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')

print (f'Your age is {age}')

我试过这个还有其他东西。有人能帮忙吗?你知道吗


Tags: 用户程序numberage错误notprinttry
3条回答

您可以在input()之后执行if语句,仍然保留except ValueError,例如:

while True:
    try:
        age=int(input('Please enter your age in years'))
        if age < 200:
            # age is valid, so we can break the loop
            break
        else:
            # age is not valid, print error, and continue the loop
            print('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
    except ValueError:
        print('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')  

可能的解决方案:

while True:
    age_input = input("Please enter your age in years: ")

    # Check both if the string is an integer, and if the age is below 200.
    if age_input.isdigit() and int(age_input) < 200:
        print("Your age is {}".format(age_input))
        break

    # If reach here, it means that the above if statement evaluated to False.
    print ("That's not a valid Number.\nPlease try Again.")

在这种情况下,不需要进行异常处理。你知道吗

isdigit()是字符串对象的方法,它告诉您给定的字符串是否只包含数字。你知道吗

首先需要检查输入的值是否为整数,请在try子句中执行此操作。 然后需要检查该值是否在范围内,在else子句中执行此操作,该子句仅在try块成功时执行。
如果值在范围内,则中断。 下面的代码显示了这一点。你知道吗

while True:
    try:
        age=int(input('Please enter your age in years'))

    except ValueError:
        print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
    else:
        if age>=200:
            print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
        else:
            break



print (f'Your age is {age}')

相关问题 更多 >

    热门问题