函數#

介紹#

函數是 Python 程式設計的基本組成部分,它將程式碼片段打包成可重複使用、高效的程式碼區塊,用於執行特定任務。函數可以在程式中多次調用,從而簡化程式碼組織,並有助於避免重複程式碼。此外,函數也使程式碼更易於調試。

重要提示: 只定義一個函數並不會讓它運作。使用 start_thread 在新執行緒中啟動函數,使其在專案啟動時立即運行,而不是等待事件或回呼。

  • def 定義一個函數。

  • return 將函數的輸出傳回主程式。

用法:

def function_name(parameters):
    # Code to execute when the function is called
    return result  # Optional, used to return a value

參數

描述

function_name

你給函數取的名字。

parameters

可選。函數呼叫時接受輸入值的變量,允許將資料傳遞給函數。

result

可選。允許函數將結果傳回給呼叫者。如果函數不包含 return 語句,則預設會傳回 None。

Note: A function must always be defined before it is called.

定義和呼叫函數#

Functions with No Parameters#

如果函數不需要輸入,你可以定義它時不帶參數。

def greeting():
    console.print("Hello!")

# Call the greeting function
greeting()

Functions with Parameters#

你也可以向函數添加參數,從而傳遞函數運行所需的資訊。

def move_square(moves):
    for index in range(moves):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

# Call the move_square function
move_square(4)

Functions with Default Arguments#

預設參數是指當函數呼叫中未提供該參數的值時,此參數將採用預設值的參數。

def move_square(moves=4):
    for index in range(moves):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

# Call the move_square function
move_square()

Return Values from Functions#

函數可以使用 return 關鍵字將資料傳回給呼叫者。這樣,您就可以在程式中擷取和使用輸出結果。

def times_two(number):
    return number * 2

# Display the return value
console.print(times_two(2))

開始執行緒#

start_thread 在新執行緒中啟動一個函數,使其在專案開始時立即開始運行。

如果使用多個 start_thread ,則這些函數將並發運行。

Usage:
start_thread(function)

範圍

描述

function

先前定義的函數的名稱。

def move_square():
    # Move in a square path
    while True:
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

def lights():
    # Blink Optical Sensor lights
    while True:
        optical_sensor.set_light(LEDStateType.ON)
        wait(0.5, SECONDS)
        optical_sensor.set_light(LEDStateType.OFF)
        wait(0.5, SECONDS)

# Start threads — Do not delete
start_thread(move_square)
start_thread(lights)