函数#

介绍#

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

Important: Defining a function alone doesn’t make it run. Use start_thread to start running a function right when your project begins, instead of waiting for an event or callback.

  • def defines a function.

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

用法:

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

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

定义和调用函数#

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#

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

def times_two(number):
    return number * 2

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

开始线程#

start_thread calls a function so it begins running right away at the start of the project.

If more than one start_thread is used, the functions will happen at the same time.

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)