Functions · Funciones
Name a block of code
- A function is named code you can use again and again.
- Make one with
def name():and an indented body. - "Calling" the function by its name runs that code.
Nombrar un bloque de código
- Una función es código con nombre que puedes usar una y otra vez.
- Crea una con
def name():y un cuerpo indentado. - "Llamar" a la función por su nombre ejecuta ese código.
Give it inputs (parameters)
- The names in the brackets are parameters — the function's inputs.
- When you call it, you pass in arguments (the real values).
- A function can take more than one parameter.
Darle entradas (parámetros)
- Los nombres entre corchetes son parámetros — las entradas de la función.
- Cuando la llamas, pasas argumentos (los valores reales).
- Una función puede tomar más de un parámetro.
def shout(word):
print(word.upper() + "!")
shout("hello")
Send back a result (return)
returnsends a value back to whoever called the function.- You can store that value or use it in an expression.
returnalso ends the function straight away.
Devolver un resultado (return)
returndevuelve un valor hacia atrás a quien llamó a la función.- Puedes almacenar ese valor o usarlo en una expresión.
returntambién termina la función inmediatamente.
def double(x):
return x * 2
result = double(5)
print(result)
return vs print
printonly shows something on the screen.returngives a value back that the rest of your code can use.- A function with no
returngives backNone.
return vs print
printsolo muestra algo en la pantalla.returndevuelve un valor que el resto de tu código puede usar.- Una función sin
returndevuelveNone.
In Cambridge pseudocode
- A
FUNCTIONreturns a value; aPROCEDUREjust does an action.
En pseudocódigo de Cambridge
- Un
FUNCTIONdevuelve un valor; unPROCEDUREsimplemente realiza una acción.
FUNCTION Add(A : INTEGER, B : INTEGER) RETURNS INTEGER
RETURN A + B
ENDFUNCTION
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello, ", Name
ENDPROCEDURE
Common mistakes
- A function returns
Noneunless you writereturn; printing is not the same as returning. - Run a function with
():greet(), notgreet. - Define a function before you call it.
Errores comunes
- Una función retorna
Nonea menos que escribasreturn; imprimir no es lo mismo que retornar. - Ejecuta una función con
():greet(), nogreet. - Define una función antes de llamarla.
Now you try
- Define each function, then the checks will call it for you.
- Use
returnto send the answer back (do notprintit).
Ahora tú intentarlo
- Define cada función, luego los checks la llamarán por ti.
- Usa
returnpara enviar la respuesta hacia atrás (noprint).
Calling a function · Llamada a una función
A call pushes a frame with its arguments; return pops it. · Una llamada empuja un marco con sus argumentos; return lo desapila.
Write a function add(a, b) that returns · retornos the sum of a and · y b. · Escribe una función add(a, b) que devuelva la suma de a y b.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function greet(name) that returns · retornos the string Hello, then the name then !. So greet("Sam") returns · retornos Hello, Sam!. · Escribe una función greet(name) que devuelva la cadena Hello, seguida del nombre y luego !. Así, greet("Sam") devuelve Hello, Sam!.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function biggest(a, b) that returns · retornos the larger of the two values. If they are equal, return either one. · Escribe una función biggest(a, b) que devuelva el valor mayor de los dos. Si son iguales, devuelve cualquiera de los dos.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write is_palindrome(word) that returns · retornos True when the word reads the same backwards (like racecar), otherwise False. · Escribe is_palindrome(word) que devuelva True cuando la palabra se lee igual al revés (como racecar), de lo contrario False.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.