string ..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

對python中raw_input()和input()的用法詳解

發(fā)布時間:2020-10-04 21:33:08 來源:腳本之家 閱讀:173 作者:jv_rookie 欄目:開發(fā)技術

最近用到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)

運行結果為:

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)

運行結果為:

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)

運行結果為:

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()的輸出結果是“值”,相當于是對raw_input()進行一個計算后的結果。

如:

print "please input something :"
m = input()
print m
print type(m)

運行結果1為:

please input something :
23
23
<type 'int'>

輸入:23,輸出:23,類型為int;

運行結果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()的結果進行轉(zhuǎn)換:

1)轉(zhuǎn)為str

print "please input something :"
m = str(input())
print m
print type(m)

運行結果為:

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

運行結果為:

please input something :
23.5
23
<type 'int'>

輸入:23.5,輸出:23,類型為int(默認為向下取整);

注:input()不可使用list轉(zhuǎn)為列表。

以上這篇對python中raw_input()和input()的用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI