python中input()与raw_input()都可以用来接收用户的输入,但是两者还是有区别的。
我们来看下他们不同的地方:
>>> input()
1
1
>>> raw_input()
1
'1'
>>> input()
'a'
'a'
>>> raw_input()
'a'
"'a'"
>>> input()
a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'a' is not defined
>>> raw_input()
a
'a'
>>> input()
1+1
2
>>> raw_input()
1+1
'1+1'
>>> input()
'a'+'a'
'aa'
>>> raw_input()
'a'+'a'
"'a'+'a'"
>>> input()
'a'+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> raw_input()
'a'+1
"'a'+1"
可见raw_put()都会转化为原始输入的字符串形式,而input()会要求用户输入合法的python表达式并且会自动的计算,如果想输入’a’却没有加引号就会被理解为未定义的变量就会报错。
那么python中提供了eval这个内建函数,可以把raw_input()的效果转换为input():
eval(raw_input()),我们看下效果:
>>> eval(raw_input())
1+1
2
但是可惜的是python3.0中raw_input被重命名为了input,也就是说:
我们想实现python2中的raw_input()直接打input()就ok;
我们想实现python2中的input()就要打eval(input())才行。