您现在的位置是:课程教程文章
python中input()转换字符串
2023-12-14 22:12课程教程文章 人已围观
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
以上就是python中input()转换字符串的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程
课程教程:python中input()转换字符串上一篇:python中ssl认证是什么?
下一篇:没有了