我被要求使用用户的出生年份创建一个法定年龄验证程序。我已设法将用户的整数输入限制为 4 位数字,但它确实允许用户输入四位数字范围内的任何数字(0、234、1234 等)。 如何强制输入 4 位数字并禁止 1940 以下的“输入”?
我尝试过 WHILE 语句、IF 语句、len() 函数,但都不起作用。
# Welcome user to the program
greeting = "Hello! Welcome to the age calculator."
print(greeting)
print("\n")
# Input current year
current_year = 2019
# Request the users year of birth and provide eg of birth year to guide user input to 4 digits
# Set integer digit limit to max 4
birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])
# Use basic sum to calculate users age using this year
age = current_year - birth_year
print(age)
# use IF statement to add legal age
if age >= 18:
print("Congrats you are old enough")
预期结果是 1940 年和当前年份之间的有效出生年份。
最佳答案
您可能还想阻止人们进入当前年份之后的年份。这会检查上限和下限。 (也可以使用
# Request the users year of birth and provide eg of birth year to guide user input to 4 digits
# Set integer digit limit to max 4
birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])
while ((birth_year <= 1940) or (birth_year >= current_year)):
print("Please try again")
birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])
# Use basic sum to calculate users age using this year
关于python - 法定年龄证明者/检查者/计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57233512/