Loading... 使用函数 `input()`时, `Python`将用户输入解读为字符串。请看下面让用户输入其年龄的解释器会话: ``` >> age input("How old are you?") How old are you? 21 >>>age ' 21 ' ``` 用户输入的是数字21,但我们请求 `Python`提供变量age的值时,它返回的是'21′——用户输入的数值的字符串表示。我们怎么知道 `Python`将输入解读成了字符串呢?因为这个数字用引号括起了。如果我们只想打印输入,这一点问题都没有但如果你试图将输入作为数字使用,就会引发错误: ``` 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进行比较(见❷) 为解决这个问题,可使用函数`int()`,它让 `Python`将输入视为数值。函数`int()`将数字的字符串表示转换为数值表示,如下所示: ``` >> age input("How old are you?") How old are you? 21 ❶ >>> age =int(age) >> age >=18 True ``` 在这个示例中,我们在提示时输入21后, `Python`将这个数字解读为字符串,但随后`int()`将这个字符串转换成了数值表示(见❶)。这样 `Python`就能运行件测试了:将`变量age`(它现在包含数值21)同18进行比较,看它是否大于或等于18。测试结果为True 如何在实际程序中使用函数`int()`呢?请看下面的程序,它判断一个人是否满足坐过山车的身高要求: ``` `rollercoaster.py` height= input("How tall are you, in inches?") height= int(height) nt) if height >=36: print("\nYou're tall enough to ridel") else: print("\nYou'll be able to ride when you're a little older.") ``` 在这个程序中,为何可以将 height同36进行比较呢?因为在比较前, `height=int(height)` 将输入转换成了数值表示。如果输入的数字大于或等于36,我们就告诉用户他满足身高条件: ``` How tall are you, in inches? 71 You're tall enough to ride! ``` 将数值输入用于计算和比较前,务必将其转换为数值表示。 最后修改:2020 年 03 月 09 日 07 : 09 PM © 允许规范转载