Scope & arguments
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Local variables
- A variable made inside a function is local.
- It only exists while the function runs.
- Code outside the function cannot see it.
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.
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.
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.
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
BYVALpasses a copy (caller unchanged);BYREFshares the same data (caller changed).
PROCEDURE Increase(BYREF n : INTEGER)
n ← n + 1
ENDPROCEDURE
PROCEDURE Show(BYVAL n : INTEGER)
OUTPUT n
ENDPROCEDURE
Now you try
- The checks call your function with different arguments.
- Press Check answer to test your code.
Write greet(name, greeting="Hi") that returns greeting, then , , then name, then !. So greet("Sam") is Hi, Sam! and greet("Sam", "Hello") is Hello, Sam!.
Click Run to see the output here.
Write add_item(lst, x) that appends x to the list lst. Do not return anything — the caller's list should change because lists are mutable.
Click Run to see the output here.
Write between(low, high, x) that returns True if x is from low to high (inclusive), otherwise False.
Click Run to see the output here.