Scope & arguments · Alcance y argumentos
Local variables
- A variable made inside a function is local.
- It only exists while the function runs.
- Code outside the function cannot see it.
Variables locales
- Una variable creada dentro de una función es local.
- Solo existe mientras la función está en ejecución.
- El código fuera de la función no puede verla.
def make_message():
note = "secret"
print(note)
make_message()
# print(note) would be an error: note is local
Global variables
- A variable made outside all functions is global.
- A function can read a global value.
- To change a global inside a function you need the
globalkeyword — but it is usually cleaner toreturna value instead.
Variables globales
- Una variable creada fuera de todas las funciones es global.
- Una función puede leer un valor global.
- Para modificar un valor global dentro de una función se necesita la palabra clave
global— pero generalmente es más limpio usarreturnpara devolver un valor.
Default values
- A parameter can have a default value:
def f(x, step=1):. - If the caller leaves it out, the default is used.
- Parameters with defaults come after the normal ones.
Valores por defecto
- Un parámetro puede tener un valor por defecto:
def f(x, step=1):. - Si el que llama a la función no lo incluye, se usa el valor por defecto.
- Los parámetros con valores por defecto van después de los normales.
def power(base, exp=2):
return base ** exp
print(power(5))
print(power(2, 3))
How arguments are passed
- Python passes a reference to the object you give it.
- Numbers and strings are immutable: a function cannot change the caller's value.
- Lists are mutable: changes made inside a function do affect the caller's list.
Cómo se pasan los argumentos
- Python pasa una referencia al objeto que le das.
- Los números y las cadenas son inmutables: una función no puede cambiar el valor del que llama.
- Las listas son mutables: los cambios hechos dentro de una función sí afectan a la lista del que llama.
def try_change(n):
n = n + 100 # changes only the local copy
print(n)
x = 5
try_change(x)
print(x) # x is still 5
In Cambridge pseudocode (A-Level 9618)
BYVALpasses a copy (caller unchanged);BYREFshares the same data (caller changed).- ⚠️ These two keywords are A-Level 9618 only. IGCSE 0478 passes every parameter by value; to send a result back you use a
FUNCTIONandRETURNit.
En pseudocódigo de Cambridge (A-Level 9618)
BYVALpasa una copia (el que llama no cambia);BYREFcomparte los mismos datos (el que llama sí cambia).- ⚠️ Estas dos palabras clave son solo para A-Level 9618. IGCSE 0478 pasa cada parámetro por valor; para enviar un resultado de vuelta se usa una
FUNCTIONy seRETURNs.
PROCEDURE Increase(BYREF N : INTEGER)
N ← N + 1
ENDPROCEDURE
PROCEDURE Show(BYVAL N : INTEGER)
OUTPUT N
ENDPROCEDURE
Common mistakes
- A variable made inside a function is local — it cannot be seen outside.
- Arguments fill the parameters in the order you write them.
- To use a result outside,
returnit and store what comes back.
Errores comunes
- Una variable creada dentro de una función es local: no se puede ver desde fuera.
- Los argumentos rellenan los parámetros en el orden en que los escribes.
- Para usar un resultado fuera, haz
returny guarda lo que devuelva.
Now you try
- The checks call your function with different arguments.
- Press Check answer to test your code.
Ahora te toca a ti
- Las comprobaciones llaman a tu función con diferentes argumentos.
- Pulsa Comprobar respuesta para probar tu código.
Arguments live in the call · Los argumentos viven en la llamada
Each call gets its own copy of the arguments — they vanish when it returns. · Cada llamada obtiene su propia copia de los argumentos —desaparecen cuando retorna.
Write greet(name, greeting="Hi") that returns · retornos greeting, then , , then name, then !. So greet("Sam") is Hi, Sam! and · y greet("Sam", "Hello") is Hello, Sam!. · Escribe greet(name, greeting="Hi") que retorne greeting, luego , , luego name, luego !. Así greet("Sam") es Hi, Sam! y greet("Sam", "Hello") es Hello, Sam!.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write add_item(lst, x) that appends x to the list lst. Do not · no return anything — the caller's list should change because lists are mutable. · Escribe add_item(lst, x) que agregue x a la lista lst. No retornes nada —la lista del llamador debe cambiar porque las listas son mutables.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write between(low, high, x) that returns · retornos True if x is from low to · hasta high (inclusive), otherwise False. · Escribe between(low, high, x) que retorne True si x está entre low y high (inclusive), de lo contrario False.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write make_countdown(start, stop=1) that returns · retornos a list counting down from start to · hasta stop. So make_countdown(3) is [3, 2, 1] and · y make_countdown(5, 3) is [5, 4, 3]. · Escribe make_countdown(start, stop=1) que retorne una lista que cuente hacia abajo desde start hasta stop. Así make_countdown(3) es [3, 2, 1] y make_countdown(5, 3) es [5, 4, 3].
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.