为什么我不能在python中比较str和int

2024-04-16 06:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + age + " years old, " + name + "!")
if age > 50:
    print ("you are to old thx ")
else:
    print ("nice age using your apportunity ")

这是我的错误结果:

What's your name? daffa
Nice to meet you daffa!
Your age? 12
So, you are already 12 years old, daffa!
Traceback (most recent call last):
   File "C:\Users\murtadho\AppData\Local\Programs\Python\Python37\x.py", line
6, in <module>
     if age > 50:
TypeError: '>' not supported between instances of 'str' and 'int'

这里发生了什么?你知道吗


Tags: tonameyouinputageyoursowhat
1条回答
网友
1楼 · 发布于 2024-04-16 06:20:17

试试这个:作为解决方案; 我已经更新了你的代码,考虑到年龄的类型只有一个整数

name = input("What's your name? ")
print("Nice to meet you " + name + "!")
while True:
    try:
        age = int(input("Your age? "))
        break
    except Exception as e:
        print("please enter a valid age")
print("So, you are already " + str(age) + " years old, " + name + "!")

if age > 50:
   print ("you are to old thx ")

else:
   print ("nice age using your apportunity ")

相关问题 更多 >