函数#
介绍#
函数是 Python 编程的基本组成部分,它将代码片段打包成可重用、高效的代码块,用于执行特定任务。函数可以在程序中多次调用,从而简化代码组织,并有助于避免重复代码。此外,函数也使代码更容易调试。
Important: Defining a function alone doesn’t make it run. Use cte_thread to start a function in a new thread so it begins running right away at the start of the project, instead of waiting for an event or callback.
defdefines a function.returnsends 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
参数 |
描述 |
|---|---|
|
你给函数起的名字。 |
|
可选。函数调用时接受输入值的变量,允许将数据传递给函数。 |
|
Optional. Lets the function send a result back to the caller. If a function does not include a return statement, it will return |
注意: 函数必须在调用之前定义**。
定义和调用函数#
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#
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
print(times_two(2))
cte_thread#
cte_thread starts a function in a new thread so it begins running right away at the start of the project.
If more than one cte_thread is used, the functions will run concurrently.
Usage:
cte_thread(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, signal_tower.BLINK)
# Start threads — Do not delete
cte_thread(move_square)
cte_thread(lights)