功能#
介紹#
函數是 Python 程式設計的基本組成部分,它將程式碼片段打包成可重複使用、高效的程式碼區塊,用於執行特定任務。函數可以在程式中多次調用,從而簡化程式碼組織,並有助於避免重複程式碼。此外,函數也使程式碼更易於調試。
def定義一個函數。return將函數的輸出傳回主程式。
用法:
def function_name(parameters):
# Code to execute when the function is called.
return result # Optional, used to return a value.
參數 |
描述 |
|---|---|
|
您為您的函數指定的名稱。 |
|
可選。函數呼叫時接受輸入值的變量,允許將資料傳遞到函數中。 |
|
可選。允許函數將結果傳回給呼叫者。如果函數不包含 return 語句,則預設會傳回 |
注意:函數必須始終在*呼叫之前定義。
定義和呼叫函數#
Functions with No Parameters#
如果函數不需要輸入,則可以定義不帶參數的函數。
# Define a function to display a message.
def greeting():
controller.screen.print("Hello!")
# Call the function to display the message.
greeting()
Functions with Parameters#
您也可以為函數新增參數,以便傳遞函數運行所需的資訊。
# Define a function with a parameter.
def named_greeting(name):
controller.screen.print("Hello, " + name + "!")
named_greeting("Stranger")
Functions with Default Arguments#
預設參數是如果函數呼叫中未提供該參數的值,則採用預設值的參數。
# Define a function with a parameter and a default argument.
def named_greeting(name = "Stranger"):
controller.screen.print("Hello, " + name + "!")
# Use the default argument.
named_greeting()
controller.screen.next_row()
# Change the parameter to a different name.
named_greeting("AIR")
Return Values from Functions#
函數可以使用 return 關鍵字將資料傳回給呼叫者。這樣,您就可以在程式中擷取和使用輸出結果。
# Define a function that multiplies numbers by 2.
def times_two(number):
return number * 2
# Display the return value.
controller.screen.print(times_two(2))