什么是輸入
咱們在銀行ATM機器前取錢時,肯定需要輸入密碼,對不?
那么怎樣才能讓程序知道咱們剛剛輸入的是什么呢??
大家應該知道了,如果要完成ATM機取錢這件事情,需要先從鍵盤中輸入一個數據,然后用一個變量來保存,是不是很好理解啊
1、python2的輸入語句
在python2中有兩種常見的輸入語句,input()
和raw_input()
。
(1)input()函數
可以接收不同類型的參數,而且返回的是輸入的類型。如,當你輸入int類型數值,那么返回就是int型;其中字符型需要用單引號或雙引號,否則,報錯。
a.數值型輸入
>>> a = input()>>> type(a)<type 'int'>>>> a>>> 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()>>> type(a)<type 'str'>>>> a'1'>>> a = raw_input()'hello'>>> type(a)<type 'str'>>>> a"'hello'"
如果想要int類型數值時,可以通過調用相關函數轉化。
>>> a = int(raw_input())>>> type(a)<type 'int'>>>> a>>> a = float(raw_input())1.23>>> type(a)<type 'float'>>>> a1.23
在同一行中輸入多個數值,可以有多種方式,這里給出調用map()
函數的轉換方法。map使用方法請參考python-map的用法
>>> a, b = map(int, raw_input().split())20>>> a>>> b>>> l = list(map(int, raw_input().split()))2 3 4>>> l[1, 2, 3, 4]
(3)input() 和raw_input()的區別
通過查看input()
幫助文檔,知道input函數也是通過調用raw_input函數實現的,區別在于,input函數額外調用內聯函數eval()。eval使用方法參考Python eval 函數妙用 (見下面)
新聞熱點
疑難解答