如果不能正常工作

时间:2016-01-06 13:51:30

标签: python

我试图创建一个简单的程序,我要求用户放置nameage,然后使用if else打印结果。

我希望什么时候年满20岁,所以结果应该来

  

祝贺编辑你的年龄是20岁,你可以找到真相

但这里没有用的是我正在使用的代码。

代码

name = input("what is your name \n")
print('Nice to meet you', name, "!!")
age = input("Your Age ? \n")

if age > 18:
    print('Congratulation ' + name + ' your age is '+ str(age), ' and you can find the truth ')
else:
    print('Sorry ' + name + 'your age is '+ str(age), ' and you can also find the truth if you start from today')

以及我在运行代码后遇到的错误。

错误

what is your name 
Edit
Nice to meet you Edit !!
Your Age ? 
20
Traceback (most recent call last):
  File "C:/Users/hp/PycharmProjects/Project/input_user.py", line 5, in <module>
    if age > 18:
TypeError: unorderable types: str() > int()

帮我解决这个问题。

1 个答案:

答案 0 :(得分:5)

阅读错误消息:

TypeError: unorderable types: str() > int()

您正在尝试比较字符串和整数。您必须先将输入转换为int

age = int(input("Your Age ? \n"))

这将允许您将其与数字进行比较。

或者,当您需要与数字进行比较时将其转换

if int(age) > 18:

但现在这更像是一个可用性问题。最好只要你得到它就把它简单地转换为int,因为年龄你可能需要的数值超过字符串值。

相关问题