天天看點

Python 中raw_input() 與 input()差別

這兩個均是 python 的内建函數,通過讀取控制台的輸入與使用者實作互動。但他們的功能不盡相同。舉兩個小例子。

Python 中raw_input() 與 input()差別

1 >>> raw_input_A = raw_input("raw_input: ")

2 raw_input: abc

3  >>> input_A = input("Input: ")

4 Input: abc

5

6 Traceback (most recent call last):

7  File "<pyshell#1>", line 1, in <module>

8    input_A = input("Input: ")

9  File "<string>", line 1, in <module>

10 NameError: name 'abc' is not defined

11  >>> input_A = input("Input: ")

12 Input: "abc"

13  >>>

Python 中raw_input() 與 input()差別
Python 中raw_input() 與 input()差別

1 >>> raw_input_B = raw_input("raw_input: ")

2 raw_input: 123

3  >>> type(raw_input_B)

4  <type 'str'>

5 >>> input_B = input("input: ")

6 input: 123

7 >>> type(input_B)

8 <type 'int'>

9 >>>

Python 中raw_input() 與 input()差別

例子 1 可以看到:這兩個函數均能接收 字元串 ,但 raw_input() 直接讀取控制台的輸入(任何類型的輸入它都可以接收)。而對于

input() ,它希望能夠讀取一個合法的 python 表達式,即你輸入字元串的時候必須使用引号将它括起來,否則它會引發一個

SyntaxError 。

例子 2 可以看到:raw_input() 将所有輸入作為字元串看待,傳回字元串類型。而 input()

在對待純數字輸入時具有自己的特性,它傳回所輸入的數字的類型( int, float );同時在例子 1 知道,input() 可接受合法的

python 表達式,舉例:input( 1 + 3 ) 會傳回 int 型的 4 。

檢視 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() 來與使用者互動。

上一篇: List
下一篇: list