gpt4 book ai didi

python - 为什么我的 if age 语法不起作用? (初学者 Python)

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:40 26 4
gpt4 key购买 nike

好吧,这是我使用 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()

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

关于python - 为什么我的 if age 语法不起作用? (初学者 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com