首页 > 编程笔记

Python input()函数的用法

我们知道 print() 函数是用来输出数据的,而 input() 函数则是让使用者从键盘输入数据,然后把使用者所输入的数值、字符或字符串传送给指定的变量。

要从键盘输入数据十分简单,语法如下。

变量 = input( 提示字符串)

当输入数据并按下 Enter 键后,就会将输入的数据指定给变量。上述语法中的“提示字符串”是一段告知使用者输入的提示信息,例如,希望使用者输入年龄,再用 print() 函数输出年龄,程序代码如下。
age = input("请输入你的年龄:")
print (age)
输出结果:

请输入你的年龄:36
36

在此还要注意,使用者输入的数据一律被视为字符串,可以通过内置的 int()、float()、bool() 等函数将输入的字符串转换为整数、浮点数或布尔值类型。

例如,下列程序代码的测试。
price =input(" 请输入产品价格:")
print(" 涨价10 元后的产品价格:")
print(price+10)
上面的程序将会因为字符串无法与数值相加而产生错误提示,输出结果为:

>>> price =input(" 请输入产品价格:")
请输入产品价格:60
>>> print(" 涨价10 元后的产品价格:")
涨价10 元后的产品价格:
>>> print(price+10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>>

这是因为输入的变量 price 是字符串,无法与数值 “10” 相加,所以必须在进行相加运算前用 int() 函数将字符串强制转换为整数类型,如此一来才可以正确地进行运算。

修正的程序代码如下所示。
price =input(" 请输入产品价格:")
print(" 涨价10 元后的产品价格:")
print (int(price)+10)

由以下示例可以看出,如果输入的字符串没有先通过 int() 函数转换成整数就直接进行加法运算,其产生的结果会变成两个字符串相加,从而造成错误的输出结果。

【示例1】将输入的字符串转换成整数类型。代码如下:
no1=input(" 请输入甲班全班人数:")
no2=input(" 请输入乙班全班人数:")
total1=no1+no2
print(type(total1))
print(" 两班总人数为%s" %total1)
total2=int(no1)+int(no2)
print(type(total2))
print(" 两班总人数为%d" %total2)
输出结果:

请输入甲班全班人数:50
请输入乙班全班人数:60
<class 'str'>
两班总人数为5060
<class 'int'>
两班总人数为110

程序解说:

优秀文章