Python input函數(shù)實現(xiàn)獲取鍵盤輸入的字符串流程講解
input()
input() 是 Python 的內(nèi)置函數(shù),用于從控制臺讀取用戶輸入的內(nèi)容。input() 函數(shù)總是以字符串的形式來處理用戶輸入的內(nèi)容,所以用戶輸入的內(nèi)容可以包含任何字符。
input() 函數(shù)的用法為:
str = input(tipmsg)
說明:
- str 表示一個字符串類型的變量,input 會將讀取到的字符串放入 str 中。
- tipmsg 表示提示信息,它會顯示在控制臺上,告訴用戶應該輸入什么樣的內(nèi)容;如果不寫 tipmsg,就不會有任何提示信息。
【實例】input() 函數(shù)的簡單使用:
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))運行結(jié)果示例:
Enter a number: 100 ↙
Enter another number: 45 ↙
aType: <class 'str'>
bType: <class 'str'>
resultValue: 10045
resultType: <class 'str'>
↙表示按下回車鍵,按下回車鍵后 input() 讀取就結(jié)束了。
本例中我們輸入了兩個整數(shù),希望計算出它們的和,但是事與愿違,Python 只是它們當成了字符串,+起到了拼接字符串的作用,而不是求和的作用。
我們可以使用 Python 內(nèi)置函數(shù)將字符串轉(zhuǎn)換成想要的類型,比如:
- int(string) 將字符串轉(zhuǎn)換成 int 類型;
- float(string) 將字符串轉(zhuǎn)換成 float 類型;
- bool(string) 將字符串轉(zhuǎn)換成 bool 類型。
修改上面的代碼,將用戶輸入的內(nèi)容轉(zhuǎn)換成數(shù)字:
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))運行結(jié)果:
Enter a number: 12.5 ↙
Enter another number: 64 ↙
aType: <class 'float'>
bType: <class 'int'>
resultValue: 76.5
resultType: <class 'float'>
關(guān)于 Python 2.x
上面講解的是 Python 3.x 中 input() 的用法,但是在較老的 Python 2.x 中情況就不一樣了。Python 2.x 共提供了兩個輸入函數(shù),分別是 input() 和 raw_input():
- Python 2.x raw_input() 和 Python 3.x input() 效果是一樣的,都只能以字符串的形式讀取用戶輸入的內(nèi)容。
- Python 2.x input() 看起來有點奇怪,它要求用戶輸入的內(nèi)容必須符合 Python 的語法,稍有疏忽就會出錯,通常來說只能是整數(shù)、小數(shù)、復數(shù)、字符串等。
比較強迫的是,Python 2.x input() 要求用戶在輸入字符串時必須使用引號包圍,這有違 Python 簡單易用的原則,所以 Python 3.x 取消了這種輸入方式。
修改本節(jié)第一段代碼,去掉 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'>
到此這篇關(guān)于Python input函數(shù)實現(xiàn)獲取鍵盤輸入的字符串流程講解的文章就介紹到這了,更多相關(guān)Python獲取輸入的字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例
這篇文章主要為大家介紹了Caffe數(shù)據(jù)可視化環(huán)境python接口配置教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

