wangjuju123

2018-11-28   阅读量: 903

数据分析师 Python编程

使用int()来获取数值输入

扫码加入数据分析学习群

使用函数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)

if height >= 36:
print("\nYou're tall enough to ride!")
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!

将数值输入用于计算和比较前,务必将其转换为数值表示。

添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
0.0000 0 2 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子