2011-02-06 62 views
274

python3.x中raw_input()input()和有什麼不一樣?python3.x中raw_input()和input()之間的區別是什麼?

+1

如何製作兼容Python 2和Python 3的輸入程序? – 2016-05-04 12:08:31

+1

爲此,您嘗試將`input`設置爲`raw_input`並忽略名稱錯誤。 – 2016-05-04 14:38:52

+1

查看'six'庫以獲取Python 2和3的兼容性。 – 2017-11-02 21:37:05

回答

325

區別在於Python 3.x中不存在raw_input(),而input()則不存在。實際上,舊的raw_input()已重命名爲input(),而舊的input()已不存在,但可以通過使用eval(input())輕鬆進行模擬。 (請記住,eval()是邪惡的,所以如果嘗試使用解析您的輸入可能的話最安全的方法。)

+55

「raw_input」...有什麼區別?「 - 「不同的是,沒有`raw_input`。」 ...相當大的差異,我會說! – 2015-02-10 21:03:05

170

在Python ,raw_input()返回一個字符串,並input()嘗試運行輸入作爲Python表達式。

由於得到一個字符串幾乎總是你想要的,所以Python 3用input()這樣做。正如斯文所說,如果你想要老行爲,eval(input())的作品。

94

的Python 2:

  • raw_input()將用戶輸入的到底是什麼,並將其回爲一個字符串。

  • input()先取raw_input(),然後再對其執行eval()

的主要區別在於input()預計語法正確的蟒蛇聲明,其中raw_input()沒有。

的Python 3:

  • raw_input()更名爲input()所以現在input()返回精確的字符串。
  • 舊的input()已被刪除。

如果你想使用舊input(),這意味着你需要評估用戶輸入作爲一個python語句,你必須使用eval(input())做手工。

4

我想補充一點細節給大家提供的解釋爲python 2用戶raw_input(),到目前爲止,您知道該函數將用戶輸入的數據作爲字符串進行評估。這意味着python不會嘗試再次理解輸入的數據。所有它會考慮的是輸入的數據將是字符串,無論它是否是實際的字符串或int或任何東西。

另一方面input()試圖瞭解用戶輸入的數據。所以像helloworld這樣的輸入甚至會將錯誤顯示爲'helloworld is undefined'。

總之,對於python 2,要輸入一個字符串,您需要輸入它,如'helloworld',這是python使用字符串時常用的結構。

20

在Python 3中,raw_input()不存在,這已經被Sven提及。

在Python 2中,input()函數會評估您的輸入。

實施例:

name = input("what is your name ?") 
what is your name ?harsha 

Traceback (most recent call last): 
    File "<pyshell#0>", line 1, in <module> 
    name = input("what is your name ?") 
    File "<string>", line 1, in <module> 
NameError: name 'harsha' is not defined 

在上面的例如,Python 2.x的正試圖評估戒作爲變量而不是字符串。爲了避免這種情況,我們可以使用雙引號來我們的輸入,如「戒」:

>>> name = input("what is your name?") 
what is your name?"harsha" 
>>> print(name) 
harsha 

的raw_input()

的raw_input的()`函數不評估,它只會讀不管你輸入。

實施例:

name = raw_input("what is your name ?") 
what is your name ?harsha 
>>> name 
'harsha' 

實施例:

name = eval(raw_input("what is your name?")) 
what is your name?harsha 

Traceback (most recent call last): 
    File "<pyshell#11>", line 1, in <module> 
    name = eval(raw_input("what is your name?")) 
    File "<string>", line 1, in <module> 
NameError: name 'harsha' is not defined 

在以上示例中,我只是想評估與eval功能的用戶輸入。

相關問題