input ()函数和raw_input函数允许我们通过命令行获取用户信息
input()函数用于收集用户信息,raw_input()用于搜集任何非数字信息。
input()直接获取信息,用户输入的任何内容都将按照实际的内容保存,并且Python将尝试为输入的内容匹配正确的数据类型。如果用户输入5,那么这个值将保存为整数。若输入5.0则保存为浮点数。
>>> number = input()
5
>>> number
5
input()函数不能接受没有引号括住的字符串。
>>> s = input()
Hello
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s = input()
File "<string>", line 1, in <module>
NameError: name 'Hello' is not defined
>>> s = input()
"Hello"
raw_input()把用户输入的任何内容都保存为一个字符串
>>> number = raw_input()
5
>>> number
'5'
一般来说,使用raw_input()比使用input()更安全一些,使用input()时,如果Python不能转换用户所输入的内容,程序将会停止运行。
>>> age = input()
5 years
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
age = input()
File "<string>", line 1
5 years
^
SyntaxError: unexpected EOF while parsing