python input()與raw_input()

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())才行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章