Skip to main content
 首页 » 编程设计

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

2025年05月04日16EasonJim

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

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