函数#

介绍#

函数是 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

参数

描述

function_name

你给函数起的名字。

parameters

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

result

可选。允许函数将结果返回给调用者。如果函数不包含 return 语句,则默认情况下将返回 None。

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)

范围

描述

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)