Python 的 input() 与 raw_input()
Python中用于接收键盘输入的方法有input()与raw_input()。
input()方法被调用时,程序会被暂停直到用户以enter键结束输入。
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are are already " + str(age) + " years old, " + name + "!")
run
What's your name? "Frank"
Nice to meet you Frank!
Your age? 30
So, you are are already 30 years old, Frank!
input()只能读取一个合法的python表达式,一旦字符串输入缺少引号或者其它问题程序将会抛出SyntaxError 异常。
下面比教raw_input()方法
>>> raw_input_test = raw_input("raw_input: ")
raw_input: 123
>>> type(raw_input_test)
<type 'str'>
>>> input_test = input("input: ")
input: 123
>>> type(input_test)
<type 'int'>
raw_input() 将所有输入作为字符串看待,返回字符串类型。而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型(int, float甚至是tuple,list等)。
由官方文档 Built-in Functions 可知:
input([prompt])
Equivalent to eval(raw_input(prompt))
input() 本质上还是使用 raw_input() 来实现的,只是调用完 raw_input() 之后再调用 eval() 函数,所以它会计算表达式的值并返回它。
例如:
>>> age = raw_input("Your age? ")
Your age? 38
>>> print(age, type(age))
('38', <type 'str'>)
>>>
>>> age = int(raw_input("Your age? "))
Your age? 42
>>> print(age, type(age))
(42, <type 'int'>)
>>>
>>> programming_language = raw_input("Your favourite programming languages? ")
Your favourite programming languages? ["Python", "Lisp","C++"]
>>> print(programming_language, type(programming_language))
('["Python", "Lisp","C++"]', <type 'str'>)
>>>
>>> programming_language = eval(raw_input("Your favourite programming languages? "))
Your favourite programming languages? ["Python", "Lisp","C++"]
>>> print(programming_language, type(programming_language))
(['Python', 'Lisp', 'C++'], <type 'list'>)