函数#

介绍#

函数是 Python 编程的基本组成部分,它将代码片段打包成可重用、高效的代码块,用于执行特定任务。函数可以在程序中多次调用,从而简化代码组织,并有助于避免重复代码。此外,函数也使代码更容易调试。

以下是所有可用的函数资源列表:

  • def – Defines a function.

  • return – Sends the function’s output back to the main program.

  • vr_threads – Execute functions at the start of a project.

用法:

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

参数

描述

function_name

你给函数起的名字。

parameters

可选。函数调用时接受输入值的变量,允许将数据传递给函数。

result

Optional. Let the function send a result back to the caller. If a function does not include a return statement, it will return None by default.

注意: 函数必须在调用之前定义**。

定义和调用函数#

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#

Functions can send data back to the caller using the return keyword. This allows you to capture and use the output in your program.

# 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 函数必须用于调用脚本全局级别的函数。

You can take any function you have made previously, and pass it to vr_thread() at the global level. Calling at least one function inside of this is required to run a program. You do not need to do all function calls with vr_thread(), just ones that are at the global level.

If more than one vr_thread() call is made, the functions will execute in parallel.

这些函数通常会按照调用顺序执行。但是,如果某个函数需要等待,它会将执行权传递给下一个函数,并在该函数执行完毕或该函数也需要等待时继续执行。

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

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