Python input() 函式



Python 的 **input() 函式** 提供了一種從使用者接收輸入的方式。它會暫停程式執行,等待使用者提供所需的輸入。您還可以使用提示引數在輸入前向用戶顯示自定義訊息。

**input()** 函式是常用的 內建函式 之一,您可以直接使用此方法,無需匯入任何 模組。它接受任何型別的資料,但返回以字串格式給定的資料。

有一些函式與 **input()** 一起使用(例如 int()float() 等),以將給定的輸入轉換為特定型別的格式。

語法

以下是 Python input() 函式的語法:

input(message)

引數

Python input() 函式接受一個引數:

  • message − 它表示一個 字串,提供與使用者輸入相關的資訊。

返回值

Python input() 函式返回一個包含使用者輸入的字串。

input() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **input()** 函式

示例:input() 函式的使用

以下示例演示如何使用 Python 的 **input()** 函式。這裡我們定義一個字串並應用 input() 函式將其轉換為包含輸入字元的字串。結果將與原始字串相同,因為它已經包含 ASCII 字元。

orgName = input("Enter your organisation name: ")
print(f"Welcome to, {orgName}")  

執行上述程式後,它將要求輸入組織名稱。當我們在輸入名稱後按 Enter 鍵時,它將列印以下結果:

Enter your organisation name: Tutorialspoint
Welcome to, Tutorialspoint

示例:使用 input() 函式輸入整數和浮點數

要輸入 Python 中的資料型別,我們需要使用 input() 函式並將其包裝到相應的型別轉換函式中。在這個例子中,我們正在輸入整數和浮點型別。

numbOne = float(input("Enter first num: "))
numbTwo = int(input("Enter second num: "))

addition = numbOne + numbTwo
print(f"The sum of {numbOne} and {numbTwo} is {addition}")  

執行上述程式時,它將提示使用者輸入值:

Enter first num: 25.6
Enter second num: 52
The sum of 25.6 and 52 is 77.6

示例:持續提示使用者輸入

在下面的示例中,程式將持續詢問使用者輸入,直到他們輸入“exit”。

while True:
   userInp = input("Enter 'exit' to quit: ")
   if userInp.lower() == "exit":
      break
   else:
      print("Entered value:", userInp)  

執行上述程式時,它將提示使用者輸入值:

Enter 'exit' to quit: 5
Entered value: 5
Enter 'exit' to quit: TP
Entered value: TP
Enter 'exit' to quit: exit
python_built_in_functions.htm
廣告