input() 是 Python 的內置函式,用于從控制臺讀取用戶輸入的內容,input() 函式總是以字串的形式來處理用戶輸入的內容,所以用戶輸入的內容可以包含任何字符,
input() 函式的用法為:
str = input(tipmsg)
說明:
- str 表示一個字串型別的變數,input 會將讀取到的字串放入 str 中,
- tipmsg 表示提示資訊,它會顯示在控制臺上,告訴用戶應該輸入什么樣的內容;如果不寫 tipmsg,就不會有任何提示資訊,
【實體】input() 函式的簡單使用:
a = input("Enter a number: ") b = input("Enter another number: ") print("aType: ", type(a)) print("bType: ", type(b)) result = a + b print("resultValue: ", result) print("resultType: ", type(result))
運行結果示例:
Enter a number: 100↙
Enter another number: 45↙
aType: <class 'str'>
bType: <class 'str'>
resultValue: 10045
resultType: <class 'str'>
↙表示按下回車鍵,按下回車鍵后 input() 讀取就結束了,
本例中我們輸入了兩個整數,希望計算出它們的和,但是事與愿違,Python 只是它們當成了字串,+起到了拼接字串的作用,而不是求和的作用,
我們可以使用 Python 內置函式將字串轉換成想要的型別,比如:
- int(string) 將字串轉換成 int 型別;
- float(string) 將字串轉換成 float 型別;
- bool(string) 將字串轉換成 bool 型別,
修改上面的代碼,將用戶輸入的內容轉換成數字:
a = input("Enter a number: ") b = input("Enter another number: ") a = float(a) b = int(b) print("aType: ", type(a)) print("bType: ", type(b)) result = a + b print("resultValue: ", result) print("resultType: ", type(result))
運行結果:
Enter a number: 12.5↙
Enter another number: 64↙
aType: <class 'float'>
bType: <class 'int'>
resultValue: 76.5
resultType: <class 'float'>
關于 Python 2.x
上面講解的是 Python 3.x 中 input() 的用法,但是在較老的 Python 2.x 中情況就不一樣了,Python 2.x 共提供了兩個輸入函式,分別是 input() 和 raw_input():
- Python 2.x raw_input() 和 Python 3.x input() 效果是一樣的,都只能以字串的形式讀取用戶輸入的內容,
- Python 2.x input() 看起來有點奇怪,它要求用戶輸入的內容必須符合 Python 的語法,稍有疏忽就會出錯,通常來說只能是整數、小數、復數、字串等,
比較強迫的是,Python 2.x input() 要求用戶在輸入字串時必須使用引號包圍,這有違 Python 簡單易用的原則,所以 Python 3.x 取消了這種輸入方式,
修改本節第一段代碼,去掉 print 后面的括號:
a = input("Enter a number: ") b = input("Enter another number: ") print "aType: ", type(a) print "bType: ", type(b) result = a + b print "resultValue: ", result print "resultType: ", type(result)
在 Python 2.x 下運行該代碼:
Enter a number: 45↙
Enter another number: 100↙
aType: <type 'int'>
bType: <type 'int'>
resultValue: 145
resultType: <type 'int'>
結尾福利
這里免費送大家一套2020最新python入門到高級專案實戰視頻教程,點擊這里即可領取!或者加入博主Python交流圈(QQ群:1049600759)免費下載,
本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/207962.html
標籤:其他
上一篇:程式人生|從網癮少年到微軟、BAT、位元組offer收割機逆襲之路
下一篇:050_面向物件
