您的位置:首页 > 编程语言 > Python开发

python input()与raw_input()

2016-03-31 15:06 471 查看
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())才行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python