函數#
介紹#
函數是 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():
robot.screen.print("Hello!")
# Call the function to display the message
greeting()
Functions with Parameters#
你也可以向函數添加參數,從而傳遞函數運行所需的資訊。
# Define a function with a parameter
def named_greeting(name):
robot.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"):
robot.screen.print("Hello, " + name + "!")
# Use the default argument
named_greeting()
robot.screen.next_row()
# Change the parameter to a different name
named_greeting("AIM")
Return Values from Functions#
函數可以使用 return 關鍵字將資料傳回給呼叫者。這樣,您就可以在程式中擷取和使用輸出結果。
# Define a function that multiplies numbers by 2
def times_two(number):
return number * 2
# Display the return value
robot.screen.print(times_two(2))