当I';你用python写的代码没有错吗?
#我已经编写了一个代码,它应该检查用户的年龄(不允许年龄:1-17)。我的问题是,当我运行它时,它显示在每个数字(“欢迎”),甚至1-17。我认为问题出在if语句的某个地方。代码应该像这样运行:如果用户未成年(1-17岁),则打印(“您不允许输入”)。Else(17以上)打印(“欢迎”)当I';你用python写的代码没有错吗?,python,Python,#我已经编写了一个代码,它应该检查用户的年龄(不允许年龄:1-17)。我的问题是,当我运行它时,它显示在每个数字(“欢迎”),甚至1-17。我认为问题出在if语句的某个地方。代码应该像这样运行:如果用户未成年(1-17岁),则打印(“您不允许输入”)。Else(17以上)打印(“欢迎”) 与其使用一个年龄限制变量来列出所有受限制的年龄,不如这样做不是更好吗 if age > 17: print("Welcome") else: print("You're not allowed t
与其使用一个年龄限制变量来列出所有受限制的年龄,不如这样做不是更好吗
if age > 17:
print("Welcome")
else:
print("You're not allowed to enter")
您需要使用
in/notin
操作符来测试元组中是否有内容,而不是==/=代码>
if age not in age_restriction:
print("Welcome")
else:
print("You're not allowed to enter")
它给出了错误的结果,因为age
不是一个元组,而是一个数字。另一方面,age\u restrictions
是多个整数的元组,因此age
永远不会等于age\u restrictions
变量
您可以在
元组中使用对象而不是
age_restriction = range(0, 17);
if age not in age_restriction:
print("Welcome")
else:
print ("You're not allowed to enter")
或者简单地将年龄限制变量设置为18,并具有以下内容
age_restriction = 18;
if age >= age_restriction:
print("Welcome")
else:
print ("You're not allowed to enter")
要更直接地解决问题,必须在
操作符中使用python,如下所示:
if age in age_restriction:
print ("Your not allowed to enter")
else:
print("Welcome")
正如巴勃罗所说,最好的做法是检查这个数字是否小于18岁年龄限制
是将单个数字与一组数字进行比较。如果年龄不在年龄限制中,您可以使用:这将检查数字age
是否包含在元组age\u限制中
修复它。没有必要列一个年龄限制的清单,因为它们只是17岁以下的所有自然数
print("Hello, please enter your name:" )
name = input()
print("enter your age please: ")
age = int(input())
if (age>17):
print("Welcome")
else:
print ("Your not allowed to enter")
请修正你的缩进。另外,想想什么是年龄!=年龄限制实际上正在检查。你真的想检查这个数字是否等于一整组数字吗?是,或者相反:如果年龄==年龄限制:打印(“不允许输入”)否则:打印(“欢迎”)否。你不想检查这个数字是否等于列表,你要检查它是否在列表中。这是不同的。见巴尔马的回答1==[1,2,3]
将永远不会为真。@您错过了Carcigenicate
正在编写的程序:标量整数永远不能等于元组。它们不属于同一类型,不兼容维度,等等。事实上,我不知道这一点,因为我是Python的新手。17
可能应该是一个变量,例如mininum\u age
。哦,是的,对了,对不起,我忘了把17放在变量中。
print("Hello, please enter your name:" )
name = input()
print("enter your age please: ")
age = int(input())
if (age>17):
print("Welcome")
else:
print ("Your not allowed to enter")