參考鏈接: 從Python中控制臺獲取輸入
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'>