詳解Python input()函數:獲取用戶輸入的字符串


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)免費下載。


 

本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM