python - 法定年龄证明者/检查者/计算器

标签 python python-3.x

我被要求使用用户的出生年份创建一个法定年龄验证程序。我已设法将用户的整数输入限制为 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/

相关文章:

Python OOP : how to share a MongoDB connection with all classes

python - 元类 - 不能替换类字典

python - Pandas:读取 CSV 时强制错误

python - 如何使用多处理有效地将数据从一个数据库表插入到另一个数据库表?

Python:检索列表值内列表值的长度

python - 如何在for循环中创建一个新字典?

python-3.x - stackdriver 日志记录客户端库缺少 python 的严重性

mysql - 无法使用 pymysql 从我的 sql 数据库检索数据

python - Facebook 测试用户可以验证吗?

python - 跳过第一行的问题