12.9. Variables and parameters are localΒΆ
An assignment statement in a function creates a local variable for the variable on the left hand side of the
assignment operator. It is called local because this variable only exists inside the function and you cannot use it
outside. For example, consider again the square
function:
Try running this in Codelens. When a function is invoked in Codelens, the local scope is separated from global scope by
a blue box. Variables in the local scope will be placed in the blue box while global variables will stay in the global
frame. If you press the βlast >>β button you will see an error message. When we try to use y
on line 6 (outside the
function) Python looks for a global variable named y
but does not find one. This results in the error:
Name Error: 'y' is not defined.
The variable y
only exists while the function is being executed β we call this its lifetime. When the
execution of the function terminates (returns), the local variables are destroyed. Codelens helps you visualize this
because the local variables disappear after the function returns. Go back and step through the statements paying
particular attention to the variables that are created when the function is called. Note when they are subsequently
destroyed as the function returns.
Formal parameters are also local and act like local variables. For example, the lifetime of x
begins when
square
is called, and its lifetime ends when the function completes its execution.
So it is not possible for a function to set some local variable to a value, complete its execution, and then when it is called again next time, recover the local variable. Each call of the function creates new local variables, and their lifetimes expire when the function returns to the caller.
Check Your Understanding
- True
- Local variables cannot be referenced outside of the function they were defined in.
- False
- Local variables cannot be referenced outside of the function they were defined in.
func-7-3: True or False: Local variables can be referenced outside of the function they were defined in.
func-7-4: Which of the following are local variables? Please, write them in order of what line they are on in the code.
numbers = [1, 12, 13, 4]
def foo(bar):
aug = str(bar) + "street"
return aug
addresses = []
for item in numbers:
addresses.append(foo(item))
The local variables are
- 33
- Incorrect, look again at what is happening in producing.
- 12
- Incorrect, look again at what is happening in producing.
- There is an error in the code.
- Yes! There is an error because we reference y in the producing function, but it was defined in adding. Because y is a local variable, we can't use it in both functions without initializing it in both. If we initialized y as 3 in both though, the answer would be 33.
func-7-5: What is the result of the following code?
def adding(x):
y = 3
z = y + x + x
return z
def producing(x):
z = x * y
return z
print(producing(adding(4)))