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. Además, facilitan la depuración del código.
A continuación se muestra una lista de todos los recursos de función disponibles:
def– Defines a function.return– Sends the function’s output back to the main program.vr_threads– Execute functions at the start of a project.
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. Let 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.
# Define a function to display a message
def greeting():
brain.print("Hello!")
def main():
# Call the function to display the message
greeting()
# VR threads — Do not delete
vr_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.
# Define a function with a parameter
def named_greeting(name):
brain.print("Hello, " + name + "!")
def main():
named_greeting("Stranger")
# VR threads — Do not delete
vr_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.
# Define a function with a parameter and a default argument
def named_greeting(name = "Stranger"):
brain.print("Hello, " + name + "!")
def main():
# Use the default argument
named_greeting()
brain.new_line()
# Change the parameter to a different name
named_greeting("VR")
# VR threads — Do not delete
vr_thread(main)
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.
# Define a function that multiplies numbers by 2
def times_two(number):
return number * 2
def main():
# Display the return value
brain.print(times_two(2))
# VR threads — Do not delete
vr_thread(main)
vr_thread#
La función VR Thread debe usarse para llamar funciones a nivel global del script.
You can take any function you have made previously, and pass it to vr_thread() at the global level. Calling at least one function inside of this is required to run a program. You do not need to do all function calls with vr_thread(), just ones that are at the global level.
If more than one vr_thread() call is made, the functions will execute in parallel.
En general, las funciones se ejecutan en el orden en que se llaman. Sin embargo, si una función espera, pasará la ejecución a la siguiente función y continuará cuando la otra termine o cuando esta también espere.
# Define the function "main".
def main():
drivetrain.drive_for(FORWARD, 400, MM)
# Call VR thread for any previously defined functions.
vr_thread(main)