如果输入了负整数,我的程序应该如何创建错误?(python)

2024-05-20 00:38:36 发布

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

while True:
    try:
        name=str(input("Enter your name="))
        age=int(input("Enter your age="))

    except ValueError:
        print("error!! please enter the values again")
        continue
    else:
        break

current_year=int(input("What is the current year you are living in="))

n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")

那么,如果他/她为年龄输入一个负数,那么我如何创建一个错误消息供我使用,从而允许用户重新输入年龄


Tags: thenameyoutrueinputageyouris
2条回答

我会尝试使用while循环

while age < 0:
    age=int(input("Enter your age="))
    if age < 0:
        print('try again')

我们一直在计算用户的年龄,直到他们输入高于0的值

添加一个while循环,询问年龄是否小于零。如果满足此条件(用户输入负数),循环将继续(它将要求新的输入):

while True:
    try:
        name=input("Enter your name=")
        age=int(input("Enter your age="))
        while age < 0:
            age=int(input("Enter your age="))
        current_year=int(input("What is the current year you are living in="))

    except ValueError:
        print("error!! please enter the values again")
        continue
    else:
        break

n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")

相关问题 更多 >