Funciones#
Introducción#
Las funciones son un componente fundamental de la programación en Python, ya que empaquetan fragmentos de código en secciones reutilizables y eficientes diseñadas para realizar una tarea específica. Se pueden llamar varias veces dentro de un programa, lo que facilita la organización del código y ayuda a evitar la repetición de código. Además, las funciones facilitan la depuración del código.
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.
defdefines a function.returnsends the function’s output back to the main program.
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 misma. |
|
Opcional. Permite que la función devuelva un resultado a quien la llama. Si una función no incluye una instrucción de retorno, devolverá |
Nota: Una función debe siempre estar definida antes de ser llamada.
Definición y llamada de funciones#
Functions with No Parameters#
Si una función no requiere entrada, puede definirla sin parámetros.
def greeting():
brain.print("Hello!")
# Call the greeting function
greeting()
Functions with Parameters#
También puedes añadir parámetros a las funciones, lo que te permite pasarles la información que necesitan para funcionar.
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#
Un argumento predeterminado es un parámetro que asume un valor predeterminado si no se proporciona un valor en la llamada a la función para ese argumento.
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))
iniciar_hilo#
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)
Parámetro |
Descripción |
|---|---|
|
El nombre de una función definida previamente. |
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
start_thread(move_square)
start_thread(lights)