您好,登錄后才能下訂單哦!
本篇文章為大家展示了python中raw input失敗的原因是什么,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
這兩個均是 python 的內(nèi)建函數(shù),通過讀取控制臺的輸入與用戶實現(xiàn)交互。但他們的功能不盡相同。舉兩個小例子。
1.輸入為純數(shù)字時
input返回的是數(shù)值類型,如int,float
raw_inpout返回的是字符串類型,string類型
#!/usr/bin/python # -*- coding: UTF-8 -*- a = input('input:') print 'type of input', type(a) b = raw_input('raw_input:') print 'type of raw_input', type(b)
輸出:
input:1 type of input <type 'int'> raw_input:1 type of raw_input <type 'str'>
2.輸入為計算公式時
#!/usr/bin/python # -*- coding: UTF-8 -*- a = input('input:') print a b = raw_input('raw_input:') print b
輸出:
input:1+2 3 raw_input:1+2 1+
3.輸入為字符串時
#!/usr/bin/python # -*- coding: UTF-8 -*- b = raw_input('raw_input:') print b a = input('input:') print a
輸入a:
raw_input:a a input:a Traceback (most recent call last): File "D:/python_learning/test/cookbook/input raw_input.py", line 5, in <module> a = input('input:') File "<string>", line 1, in <module> NameError: name 'a' is not defined 輸入'a': raw_input:'a' 'a' input:'a' a
從對比中可以 看出,raw_input() 直接讀取控制臺的輸入(任何類型的輸入它都可以接收)。而對于 input() ,它希望能夠讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,否則它會引發(fā)一個 SyntaxError 。
raw_input() 將所有輸入作為字符串看待,返回字符串類型。而 input() 在對待純數(shù)字輸入時具有自己的特性,它返回所輸入的數(shù)字的類型( int, float ),input() 可接受合法的 python 表達式,舉例:input( 1 + 3 ) 會返回 int 型的 4 。
查看實現(xiàn)方式:
def input(prompt=None): # real signature unknown; restored from __doc__ """ input([prompt]) -> value Equivalent to eval(raw_input(prompt)). """ pass
input() 本質(zhì)上還是使用 raw_input() 來實現(xiàn)的,只是調(diào)用完 raw_input() 之后再調(diào)用 eval() 函數(shù),所以,你甚至可以將表達式作為 input() 的參數(shù),并且它會計算表達式的值并返回它。
不過在 Built-in Functions 里有一句話是這樣寫的:Consider using the raw_input() function for general input from users.
eval()這個函數(shù)是將字符串str當成有效的表達式來求值并返回計算結(jié)果,存在一定的風險,如果用戶輸入的是__import__('os').system('dir') ,你會發(fā)現(xiàn),當前目錄文件都會展現(xiàn)在用戶前面,那么繼續(xù)輸入open('文件名').read() ,代碼都給人看了。獲取完畢,一條刪除命令,文件消失??薨桑∫虼?,除非對 input() 有特別需要,否則一般情況下我們都是推薦使用 raw_input() 來與用戶交互。
上述內(nèi)容就是python中raw input失敗的原因是什么,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。