首页 > 文章列表 > python中input()转换字符串

python中input()转换字符串

Python input()
160 2022-08-07

1、如果只想打印输入,这一点问题都没有;但如果你试图将输入作为数字使用,就会引发错误:

>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() >= int()

试图将输入用于数值比较时,Python会引发错误,因为它无法将字符串和整数进行比较:不能将存储在age中的字符串'21'与数值18进行比较。

2、为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示,如下所示:

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True