繁体   English   中英

为什么我的年龄语法不能正常工作? (Python入门)

[英]Why is my if age syntax not working? (Beginner Python)

好吧,这是我使用python 3的第一天,我遇到了一个问题。 我的脚本应该说如果输入的年龄超过13岁,您就足够玩了,但是即使年龄小于13岁,它也说您已经足够大了。如果年龄小于13岁,控制台也应该关闭。 13

这是我的脚本:

print("How old are you?")

age = int(input())

if age >= "13":
    print("You are old enough to play! Let's get started!")
else:
    print("You are not old enough.")
    sys.exit("Oh dear")

请帮忙,谢谢。

您正在将字符串与整数进行比较:

age = int(input())

if age >= "13":

在Python 2中,字符串始终大于数字。 请改用数字:

if age >= 13:

在Python 3中,将字符串与类似整数的字符串进行比较会引发错误:

>>> 13 >= "13"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() >= str()

让您更清楚地了解自己在做什么错。

您不能将整数与引号进行比较,编译器会将其识别为字符串而不是int。

if age >= 13:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM