input()是Python的内置函数,用于从控制台读取用户输入的内容。input()函数总是以字符串的形式来处理用户输入的内容,所以用户输入的内容可以包含任何字符。
input()函数的用法为:
str = input(tipmsg)1复制代码类型:[python]
说明:
str表示一个字符串类型的变量,input会将读取到的字符串放入str中。
tipmsg表示提示信息,它会显示在控制台上,告诉用户应该输入什么样的内容;如果不写tipmsg,就不会有任何提示信息。
【实例】input()函数的简单使用:
a = input("Enter a number: ")
b = input("Enter another number: ")
print("aType: ", type(a))
print("bType: ", type(b))
result = a + b
print("resultValue: ", result)
print("resultType: ", type(result))1234567复制代码类型:[python]
运行结果示例:
Enter a number: 100↙
Enter another number: 45↙
aType: <class 'str'>
bType: <class 'str'>
resultValue: 10045
resultType: <class 'str'>123456复制代码类型:[python]
↙表示按下回车键,按下回车键后input()读取就结束了。
本例中我们输入了两个整数,希望计算出它们的和,但是事与愿违,Python只是它们当成了字符串,+起到了拼接字符串的作用,而不是求和的作用。
我们可以使用Python内置函数将字符串转换成想要的类型,比如:
int(string)将字符串转换成int类型;
float(string)将字符串转换成float类型;
bool(string)将字符串转换成bool类型。
修改上面的代码,将用户输入的内容转换成数字:
a = input("Enter a number: ")
b = input("Enter another number: ")
a = float(a)
b = int(b)
print("aType: ", type(a))
print("bType: ", type(b))
result = a + b
print("resultValue: ", result)
print("resultType: ", type(result))123456789复制代码类型:[java]
运行结果:
Enter a number: 12.5↙
Enter another number: 64↙
aType: <class 'float'>
bType: <class 'int'>
resultValue: 76.5
resultType: <class 'float'>123456复制代码类型:[java]
关于Python2.x
上面讲解的是Python3.x中input()的用法,但是在较老的Python2.x中情况就不一样了。Python2.x共提供了两个输入函数,分别是input()和raw_input():
Python2.xraw_input()和Python3.xinput()效果是一样的,都只能以字符串的形式读取用户输入的内容。
Python2.xinput()看起来有点奇怪,它要求用户输入的内容必须符合Python的语法,稍有疏忽就会出错,通常来说只能是整数、小数、复数、字符串等。
比较强迫的是,Python2.xinput()要求用户在输入字符串时必须使用引号包围,这有违Python简单易用的原则,所以Python3.x取消了这种输入方式。
修改本节第一段代码,去掉print后面的括号:
a = input("Enter a number: ")
b = input("Enter another number: ")
print "aType: ", type(a)
print "bType: ", type(b)
result = a + b
print "resultValue: ", result
print "resultType: ", type(result)1234567复制代码类型:[python]
在Python2.x下运行该代码:
Enter a number: 45↙
Enter another number: 100↙
aType: <type 'int'>
bType: <type 'int'>
resultValue: 145
resultType: <type 'int'>