首页 > 解决方案 > 当我在python中正确编写代码时,为什么控制台会给出错误的输出?

问题描述

#我写了一个代码,它应该检查用户的年龄(不允许年龄:1-17)。我的问题是,当我运行它时,它会显示在每个数字(“欢迎”)上,甚至是 1-17。我认为问题出在某处的 if 语句中。代码应该像这样运行:如果用户是未成年人(1-17 岁),则 print("You're not allowed to enter")。否则(17 岁以上)打印(“欢迎”)。

 #My code:

print("Hello, please enter your name:" )

name = input()

print("enter your age please: ")

age = int(input())
age_restriction = 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17

if age != age_restriction:
    print("Welcome")
else:
    print ("Your not allowed to enter")

标签: python

解决方案


您需要使用in/not in运算符来测试元组中是否有内容,而不是==/!=.

if age not in age_restriction:
    print("Welcome")
else:
    print("You're not allowed to enter")

推荐阅读