python - 如何在 Python 中比较字符串和整数?

标签 python string input int

<分区>

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

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 时,它总是会尝试将输入转换为整数,并且会在您输入无法转换为整数的字符串时引发 ValueError诠释。要处理这些情况,请执行以下操作:

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

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

try:
    user_input = int(input('How old are you?: '))
except ValueError:
    print('That is not a number')
else:
    if user_input >= 18:
        print('You are an adult')
    else:
        print('You are quite young')

关于python - 如何在 Python 中比较字符串和整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977659/

相关文章:

python - 在django中获取最后插入的id

r - 在 R 中将字符串修剪为特定数量的字符

html - 从 CSS 禁用文本区域

html - 如何在 HTML 输入框中突出显示实体和代码关键字?

python - 从 pony ORM 创建 postgres 数据库

python - 如何在 TensorFlow import_graph_def 期间更改输入维度

r - 如何将引号粘贴到 R 中的字符串(在列中)?

c++ - 如何在 C++ 中解析基于文本的表格

javascript - 将提示值传递到输入按钮上的 "click"事件触发的函数中

python grep 寻找一个模式,然后是之前的一些行