raw_input() 與 input() __ Python

這兩個均是 python 的內建函數,經過讀取控制檯的輸入與用戶實現交互。但他們的功能不盡相同。舉兩個小例子。html

複製代碼
  
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   >>>
複製代碼
複製代碼
  
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 >>>
複製代碼

例子 1 能夠看到:這兩個函數均能接收 字符串 ,但 raw_input() 直接讀取控制檯的輸入(任何類型的輸入它均可以接收)。而對於 input() ,它但願可以讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,不然它會引起一個 SyntaxError 。python

例子 2 能夠看到:raw_input() 將全部輸入做爲字符串看待,返回字符串類型。而 input() 在對待純數字輸入時具備本身的特性,它返回所輸入的數字的類型( int, float );同時在例子 1 知道,input() 可接受合法的 python 表達式,舉例:input( 1 + 3 ) 會返回 int 型的 4 。shell

查看 Built-in Functions ,得知:ide

input([prompt])函數

    Equivalent to eval(raw_input(prompt)) ui

input() 本質上仍是使用 raw_input() 來實現的,只是調用完 raw_input() 以後再調用 eval() 函數,因此,你甚至能夠將表達式做爲 input() 的參數,而且它會計算表達式的值並返回它。spa

不過在 Built-in Functions 裏有一句話是這樣寫的:Consider using the raw_input() function for general input from users..net

除非對 input() 有特別須要,不然通常狀況下咱們都是推薦使用 raw_input() 來與用戶交互。code

-------htm

今天參加某公司的筆試的時候,俺使用了 raw_input() 接受整數(返回的是字符串)並再用一行語句返回整型數據。杯具,當時不大肯定能用 input() 這個函數!特此記錄。

相關文章
相關標籤/搜索