1. 程式人生 > 程式設計 >Python如何使用input函式獲取輸入

Python如何使用input函式獲取輸入

所謂輸入,就是用程式碼獲取使用者通過鍵盤輸入的資訊。

例如:去銀行取錢,在 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()函式獲取的資訊都是字串型別。全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。