對python中raw_input()和input()的用法詳解
最近用到raw_input()和input()來實現(xiàn)即時輸入,就順便找了些資料來看,加上自己所用到的一些內(nèi)容,整理如下:
1、raw_input()
raw_input([prompt]) -> string
系統(tǒng)介紹中是:讀取標準輸入的字符串。因此,無論輸入的是數(shù)字或者字符或者其他,均被視為字符格式。
如:
print "Please input a num:" k = raw_input() print k print type(k)
運行結(jié)果為:
Please input a num: 23 23 <type 'str'>
輸入數(shù)字:23,輸出:23,類型為str;
因此,在不同的場景下就要求輸入的內(nèi)容進行轉(zhuǎn)換。
1)轉(zhuǎn)為int型
print "Please input a num:" n = int(raw_input()) print n print type(n)
運行結(jié)果為:
Please input a num: 23 23 <type 'int'>
輸入:23,輸出:23,類型為int;
2)轉(zhuǎn)為list型
print "please input list s:" s = list(raw_input()) print s print type(s)
運行結(jié)果為:
please input list s: 23 ['2', '3'] <type 'list'>
輸入:23,輸出:[ '2','3' ],類型為list;
如何直接生成數(shù)值型的list尚未解決,算個思考題吧。
2、input()
input([prompt]) -> value Equivalent to eval(raw_input(prompt))
可以看出,input()的輸出結(jié)果是“值”,相當于是對raw_input()進行一個計算后的結(jié)果。
如:
print "please input something :" m = input() print m print type(m)
運行結(jié)果1為:
please input something : 23 23 <type 'int'>
輸入:23,輸出:23,類型為int;
運行結(jié)果2為:
please input something : abc Traceback (most recent call last): File "D:/python test/ceshi1.py", line 24, in <module> m = str(input()) File "<string>", line 1, in <module> NameError: name 'abc' is not defined
輸入:abc,輸出報錯(字符型的輸入不通過);
但也可以把input()的結(jié)果進行轉(zhuǎn)換:
1)轉(zhuǎn)為str
print "please input something :" m = str(input()) print m print type(m)
運行結(jié)果為:
please input something : 23 23 <type 'str'>
輸入為數(shù)值型的23,輸出:23,類型為str;
2)轉(zhuǎn)為int
print "please input something :" m = int(input()) print m print ty
運行結(jié)果為:
please input something : 23.5 23 <type 'int'>
輸入:23.5,輸出:23,類型為int(默認為向下取整);
注:input()不可使用list轉(zhuǎn)為列表。
以上這篇對python中raw_input()和input()的用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python中threading開啟關(guān)閉線程操作
這篇文章主要介紹了python中threading開啟關(guān)閉線程操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Pandas統(tǒng)計計數(shù)value_counts()的使用
本文主要介紹了Pandas統(tǒng)計計數(shù)value_counts()的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
python opencv 讀取本地視頻文件 修改ffmpeg的方法
今天小編就為大家分享一篇python opencv 讀取本地視頻文件 修改ffmpeg的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

