函數#
介紹#
函數是 Python 程式設計的基本組成部分,它將程式碼片段打包成可重複使用、高效的程式碼區塊,用於執行特定任務。函數可以在程式中多次調用,從而簡化程式碼組織,並有助於避免重複程式碼。此外,函數也使程式碼更易於調試。
重要提示: 只定義一個函數並不會讓它運作。使用 cte_thread 在新執行緒中啟動函數,使其在專案啟動時立即運行,而不是等待事件或回呼。
def定義一個函數。return將函數的輸出傳回主程式。
用法:
def function_name(parameters):
# Code to execute when the function is called
return result # Optional, used to return a value
參數 |
描述 |
|---|---|
|
你給函數取的名字。 |
|
可選。函數呼叫時接受輸入值的變量,允許將資料傳遞給函數。 |
|
可選。允許函數將結果傳回給呼叫者。如果函數不包含 return 語句,則預設會傳回 |
Note: A function must always be defined before it is called.
定義和呼叫函數#
Functions with No Parameters#
如果函數不需要輸入,你可以定義它時不帶參數。
def greeting():
brain.print("Hello!")
# Call the greeting function
greeting()
Functions with Parameters#
你也可以向函數添加參數,從而傳遞函數運行所需的資訊。
def move_square(moves):
for index in range(moves):
arm.move_inc(100, 0, 0)
arm.move_inc(0, 100, 0)
arm.move_inc(-100, 0, 0)
arm.move_inc(0, 100, 0)
# Call the move_square function
move_square(4)
Functions with Default Arguments#
預設參數是指當函數呼叫中未提供該參數的值時,此參數將採用預設值的參數。
def move_square(moves=4):
for index in range(moves):
arm.move_inc(100, 0, 0)
arm.move_inc(0, 100, 0)
arm.move_inc(-100, 0, 0)
arm.move_inc(0, 100, 0)
# Call the move_square function
move_square()
Return Values from Functions#
函數可以使用 return 關鍵字將資料傳回給呼叫者。這樣,您就可以在程式中擷取和使用輸出結果。
def times_two(number):
return number * 2
# Display the return value
print(times_two(2))
cte_thread#
cte_thread 在新執行緒中啟動一個函數,使其在專案開始時立即開始運行。
如果使用多個 cte_thread ,則這些函數將會並發運行。
Usage:
cte_thread(function)
範圍 |
描述 |
|---|---|
|
先前定義的函數的名稱。 |
def move_square():
# Move in a square path
while True:
arm.move_inc(100, 0, 0)
arm.move_inc(0, 100, 0)
arm.move_inc(-100, 0, 0)
arm.move_inc(0, 100, 0)
def lights():
# Set the Signal Tower to start blinking the blue LED
signal_tower.set_color(SignalTower.BLUE, SignalTower.BLINK)
# Start threads — Do not delete
cte_thread(move_square)
cte_thread(lights)