對python中raw_input()和input()的用法詳解
最近用到raw_input()和input()來實現(xiàn)即時輸入,就順便找了些資料來看,加上自己所用到的一些內容,整理如下:
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;
因此,在不同的場景下就要求輸入的內容進行轉換。
1)轉為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)轉為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()的結果進行轉換:
1)轉為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)轉為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轉為列表。
以上這篇對python中raw_input()和input()的用法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Pycharm安裝并配置jupyter notebook的實現(xiàn)
這篇文章主要介紹了Pycharm安裝并配置jupyter notebook的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05Python Web框架Flask信號機制(signals)介紹
這篇文章主要介紹了Python Web框架Flask信號機制(signals)介紹,本文介紹Flask的信號機制,講述信號的用途,并給出創(chuàng)建信號、訂閱信號、發(fā)送信號的方法,需要的朋友可以參考下2015-01-01python3結合openpyxl庫實現(xiàn)excel操作的實例代碼
這篇文章主要介紹了python3結合openpyxl庫實現(xiàn)excel操作的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09詳解Python中常用的激活函數(shù)(Sigmoid、Tanh、ReLU等)
激活函數(shù) (Activation functions) 對于人工神經網絡模型去學習、理解非常復雜和非線性的函數(shù)來說具有十分重要的作用,這篇文章主要介紹了Python中常用的激活函數(shù)(Sigmoid、Tanh、ReLU等),需要的朋友可以參考下2023-04-04python通過TimedRotatingFileHandler按時間切割日志
這篇文章主要介紹了python通過TimedRotatingFileHandler按時間切割日志的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07使用Pandas和Matplotlib進行數(shù)據(jù)清洗與可視化的實現(xiàn)步驟
在數(shù)據(jù)科學領域,數(shù)據(jù)清洗和可視化是構建數(shù)據(jù)驅動解決方案的重要步驟,本文將詳細介紹如何使用Pandas進行數(shù)據(jù)清洗,并結合Matplotlib進行可視化,文章通過實際代碼示例講解的非常詳細,需要的朋友可以參考下2024-08-08