在python2中有兩種常見的輸入語句,input()和raw_input()。html
能夠接收不一樣類型的參數,並且返回的是輸入的類型。如,當你輸入int類型數值,那麼返回就是int型;其中字符型須要用單引號或雙引號,不然,報錯。python
a.數值型輸入shell
>>> a = input() 10 >>> type(a) <type 'int'> >>> a 10 >>> a = input() 1.23 >>> type(a) <type 'float'> >>> a 1.23
b.字符類型express
若是輸入的字符不加引號,就會報錯app
>>> r = input() hello Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> r = input() File "<string>", line 1, in <module> NameError: name 'hello' is not defined
正確的字符輸入函數
>>> r = input() 'hello' >>> r 'hello' >>> r = input() "hello" >>> r 'hello'
固然,能夠對輸入的字符加以說明post
>>> name = input('please input name:') please input name:'Tom' >>> print 'Your name : ',name Your name : Tom
函數raw_input()是把輸入的數據所有看作字符類型。輸入字符類型時,不須要加引號,不然,加的引號也會被看作字符。ui
>>> a = raw_input() 1 >>> type(a) <type 'str'> >>> a '1' >>> a = raw_input() 'hello' >>> type(a) <type 'str'> >>> a "'hello'"
若是想要int類型數值時,能夠經過調用相關函數轉化。lua
>>> a = int(raw_input()) 1 >>> type(a) <type 'int'> >>> a 1 >>> a = float(raw_input()) 1.23 >>> type(a) <type 'float'> >>> a 1.23
在同一行中輸入多個數值,能夠有多種方式,這裏給出調用map() 函數的轉換方法。map使用方法請參考python-map的用法url
>>> a, b = map(int, raw_input().split()) 10 20 >>> a 10 >>> b 20 >>> l = list(map(int, raw_input().split())) 1 2 3 4 >>> l [1, 2, 3, 4]
經過查看input()幫助文檔,知道input函數也是經過調用raw_input函數實現的,區別在於,input函數額外調用內聯函數eval()。eval使用方法參考Python eval 函數妙用
>>> help(input) Help on built-in function input in module __builtin__: input(...) input([prompt]) -> value Equivalent to eval(raw_input(prompt)). >>> help(eval) Help on built-in function eval in module __builtin__: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
python3中的輸入語句只有input()函數,沒有raw_input();並且python3中的input()函數與python2中的raw_input()的使用方法同樣。
>>> a = input() 10 >>> type(a) <class 'str'> >>> a '10'