如何在Python中比较字符串和整数? [英] How do I compare a string and an integer in Python?

查看:196
本文介绍了如何在Python中比较字符串和整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手。
我写了这个,当我在输入中输入一个字母时出现了这个错误:

I am quite a newbie in Python. I wrote this and got this error when i typed a letter in the input:

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

这是我写的代码:

user_input = input('How old are you?: ')
if user_input >= 18:
   print('You are an adult')
elif user_input < 18:
     print('You are quite young')
elif user_input == str():
     print ('That is not a number')


推荐答案

你应该这样做:

user_input = int(input('How old are you?: '))

因此,当您明确地将输入转换为int时,它总是会尝试将输入转换为整数,并在输入字符串而不是int时引发 valueError 。要处理这些情况,请执行以下操作:

so as you explicitly cast your input as int, it will always try to convert the input into an integer, and will raise a valueError when you enter a string rather than an int. To handle those cases, do:

except ValueError:
    print ('That is not a number')

因此,完整的解决方案可能如下所示:

So, the full solution might be like below:

try:
    user_input = int(input('How old are you?: '))

    if user_input >= 18:
         print('You are an adult')
    else:
         print('You are quite young')
except ValueError:
    print ('That is not a number')

这篇关于如何在Python中比较字符串和整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆