標籤:compile com 類型 調用 log put title 通過 協助
Python的輸入語句類型1 python2的輸入語句
在python2中有兩種常見的輸入語句,input()和raw_input()。
(1)input()函數
可以接收不同類型的參數,而且返回的是輸入的類型。如,當你輸入int類型數值,那麼返回就是int型;其中字元型需要用單引號或雙引號,否則,報錯。
a.數值型輸入
>>> a = input()10>>> type(a)<type ‘int‘>>>> a10>>> a = input()1.23>>> type(a)<type ‘float‘>>>> a1.23
b.字元類型
如果輸入的字元不加引號,就會報錯
>>> r = input()helloTraceback (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‘
當然,可以對輸入的字元加以說明
>>> name = input(‘please input name:‘)please input name:‘Tom‘>>> print ‘Your name : ‘,nameYour name : Tom
(2)raw_input()
函數raw_input()是把輸入的資料全部看做字元類型。輸入字元類型時,不需要加引號,否則,加的引號也會被看做字元。
>>> a = raw_input()1>>> type(a)<type ‘str‘>>>> a‘1‘>>> a = raw_input()‘hello‘>>> type(a)<type ‘str‘>>>> a"‘hello‘"
如果想要int類型數值時,可以通過調用相關函數轉化。
>>> a = int(raw_input())1>>> type(a)<type ‘int‘>>>> a1>>> a = float(raw_input())1.23>>> type(a)<type ‘float‘>>>> a1.23
在同一行中輸入多個數值,可以有多種方式,這裡給出調用map() 函數的轉換方法。map使用方法請參考python-map的用法
>>> a, b = map(int, raw_input().split())10 20>>> a10>>> b20>>> l = list(map(int, raw_input().split()))1 2 3 4>>> l[1, 2, 3, 4]
(3)input() 和raw_input()的區別
通過查看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.
2 Python3輸入語句
python3中的輸入語句只有input()函數,沒有raw_input();而且python3中的input()函數與python2中的raw_input()的使用方法一樣。
>>> a = input()10>>> type(a)<class ‘str‘>>>> a‘10‘
python2 和 pyhton3 輸入語句寫法