函數#

介紹#

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

重要提示: 只定義一個函數並不會讓它運作。使用 vr_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#

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

# Define a function to display a message
def greeting():
    brain.print("Hello!")

def main():
    # Call the function to display the message
    greeting()

# VR threads — Do not delete
vr_thread(main)

Functions with Parameters#

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

# Define a function with a parameter
def named_greeting(name):
    brain.print("Hello, " + name + "!")

def main():
    named_greeting("Stranger")

# VR threads — Do not delete
vr_thread(main)

Functions with Default Arguments#

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

# Define a function with a parameter and a default argument
def named_greeting(name = "Stranger"):
    brain.print("Hello, " + name + "!")

def main():
    # Use the default argument
    named_greeting()
    brain.new_line()
    # Change the parameter to a different name
    named_greeting("VR")

# VR threads — Do not delete
vr_thread(main)

Return Values from Functions#

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

# Define a function that multiplies numbers by 2
def times_two(number):
    return number * 2

def main():
    # Display the return value
    brain.print(times_two(2))

# VR threads — Do not delete
vr_thread(main)

vr_thread#

VR Thread 函數必須用於呼叫腳本全域層級的函數。

你可以將先前建立的任何函數傳遞給全域層級的 `vr_thread() 。程式運行需要呼叫其中至少一個函數。你不需要對所有函數呼叫都使用 vr_thread(),只要呼叫全域層級的函數即可。

如果呼叫 vr_thread() 超過一次,這些函數將會並行執行。

這些函數通常會按照呼叫順序執行。但是,如果某個函數需要等待,它會將執行權傳遞給下一個函數,並在該函數執行完畢或該函數也需要等待時繼續執行。

Usage:
vr_thread(function)

範圍

描述

function

先前定義的函數的名稱。

# Define the function "main".
def main():
    drivetrain.drive_for(FORWARD, 400, MM)

# Call VR thread for any previously defined functions.
vr_thread(main)