raw_input() 與 input() __ Python,這兩個均是 python 的內建函數,經過讀取控制檯的輸入與用戶實現交互。但他們的功能不盡相同。舉兩個小例子。html
例1:python
#!/user/bin/python # -*- coding: utf8 -*- raw_input_A = raw_input("raw_input: ") print raw_input_A
用戶鍵入abc後輸出:git
raw_input: abc abc
而windows
#!/user/bin/python # -*- coding: utf8 -*- input_A = input("Input: ") print input_A
報錯:eclipse
Input: abc Traceback (most recent call last): File "E:\git\pyTest\com\test.py", line 7, in <module> input_A = input("Input: ") File "E:\adt-bundle-windows-x86-20131030\adt-bundle-windows-x86-20131030\eclipse\plugins\org.python.pydev_2.2.0.2011062419\PySrc\pydev_sitecustomize\sitecustomize.py", line 210, in input return eval(raw_input(prompt)) File "<string>", line 1, in <module> NameError: name 'abc' is not defined
例子 1 能夠看到:這兩個函數均能接收 字符串 ,但 raw_input() 直接讀取控制檯的輸入(任何類型的輸入它均可以接收)。而對於 input() ,它但願可以讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,不然它會引起一個 SyntaxError 。ide
改成:(輸入字符串的時候加上引號則正確)函數
Input: "abc" abc
例2:ui
raw_input_B = raw_input("raw_input: ") print type(raw_input_B) input_B = input("input: ") print type(input_B)
輸出結果:spa
raw_input: 123 <type 'str'> input: 123 <type 'int'>
例子 2 能夠看到:raw_input() 將全部輸入做爲字符串看待,返回字符串類型。而 input() 在對待純數字輸入時具備本身的特性,它返回所輸入的數字的類型( int, float );同時在例子 1 知道,input() 可接受合法的 python 表達式,舉例:input( 1 + 3 ) 會返回 int 型的 4 。code
查看 Built-in Functions ,得知:
input([prompt])
Equivalent to eval(raw_input(prompt))
input() 本質上仍是使用 raw_input() 來實現的,只是調用完 raw_input() 以後再調用 eval() 函數,因此,你甚至能夠將表達式做爲 input() 的參數,而且它會計算表達式的值並返回它。
不過在 Built-in Functions 裏有一句話是這樣寫的:Consider using the raw_input() function for general input from users.
除非對 input() 有特別須要,不然通常狀況下咱們都是推薦使用 raw_input() 來與用戶交互。
-------