Funciones#
Introducción#
Functions are a fundamental component of Python programming, packaging code snippets into reusable, efficient sections of code designed to perform a specific task. Functions can be called multiple times within a program, making code organization easier, and helping to avoid repeated code. Functions also make code easier to debug.
Important: Defining a function alone doesn’t make it run. Use start_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.
defdefine una función.returnenvía la salida de la función al programa principal.
Uso:
def function_name(parameters):
# Code to execute when the function is called
return result # Optional, used to return a value
Parámetros |
Descripción |
|---|---|
|
Un nombre que le das a tu función. |
|
Opcional. Variables que aceptan valores de entrada cuando se llama a la función, lo que permite pasar datos a la función. |
|
Optional. Lets the function send a result back to the caller. If a function does not include a return statement, it will return |
Nota: Una función siempre debe definirse antes de ser llamada.
Definición y llamada de funciones#
Functions with No Parameters#
Si una función no requiere entrada, puedes definirla sin parámetros.
def greeting():
console.print("Hello!")
def main():
# Call the greeting function
greeting()
# Start threads — Do not delete
start_thread(main)
Functions with Parameters#
También puedes agregar parámetros a las funciones, lo que te permite pasar información que la función necesita para funcionar.
# Build Used: Super Code Base 2.0
def move_square(moves):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square(4)
# Start threads — Do not delete
start_thread(main)
Functions with Default Arguments#
Un argumento predeterminado es un parámetro que asume un valor predeterminado si no se proporciona un valor en la llamada de función para ese argumento.
# Build Used: Super Code Base 2.0
def move_square(moves=4):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square()
# Start threads — Do not delete
start_thread(main)
Return Values from Functions#
Las funciones pueden devolver datos al llamador mediante la palabra clave return Esto le permite capturar y usar la salida en su programa.
def times_two(number):
return number * 2
def main():
# Display the return value
console.print(times_two(2))
# Start threads — Do not delete
start_thread(main)
hilo de inicio#
start_thread starts a function in a new thread so it begins running right away at the start of the project.
If more than one start_thread is used, the functions Will run concurrently.
Uso:
start_thread(function)
Parámetros |
Descripción |
|---|---|
|
El nombre de una función definida previamente. |
# Build Used: Super Code Base 2.0
def move_square():
# Move in a square path
while True:
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def led_lights():
# Blink LED lights
while True:
bumper.set_color(GREEN)
wait(0.5, SECONDS)
bumper.set_color(RED)
wait(0.5, SECONDS)
# Start threads — Do not delete
start_thread(move_square)
start_thread(led_lights)