所謂輸入,就是用代碼獲取用戶通過鍵盤輸入的信息。
例如:去銀行取錢,在 ATM 上輸入密碼。
在 Python 中,如果要獲取用戶在鍵盤上的輸入信息,需要使用到input()函數。
函數input()讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其存儲在一個變量中,以方便使用。
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只是它們當成了字符串,+ 起到了拼接字符串的作用,而不是求和的作用。
所以,一定要謹記,input()函數獲取的信息都是字符串類型。