Lab 1 - Closures and Scope¶
Instructions: Open a new word document and document your work as you complete each task and answer each question.
In this lab, you will use codelens to investigate the concepts of a closure and the scope of a variable. You will be given a series of complicated lambda expressions and asked to use codelens to answer some associated questions.
Closures¶
When a function is that references a value outside its scope, a closure is created. Recall that a closure is a function bundled with references to each of the variables defined outside the function definition.
Referencing global variable¶
Question 1
How does changing a global variable affect a function that references this variable?
A global variable is a variable that is defined at the top level, i.e. at the interpreter prompt. Global variables differ from local variables, which are defined inside the scope of a function, which includes the formal parameters and any variable defined inside the function.
Consider the following example.
In [1]: x = 3
In [2]: f = lambda y: x**y
In [3]: f(2)
Out[3]: 9
# Now change the value of x
In [4]: x = 4
# Does this change our answer?
In [5]: f(2)
Out[5]: 16
Use codelens to step through this example and then complete Task 1.
Task 1
Where the two function calls the same or different? Use what you learned from codelens to explain your answer.
Referencing local variables¶
Question 2
How does changing a local variable affect a function that references this variable?
Now we will make a similar example, but this time letting x
be a local
variable defined outside of an inner lambda
expression.
In [6]: g = lambda x: lambda y: x**y
# "set" x to 3 with a function call
In [7]: f1 = g(3)
In [8]: f1(2)
Out[8]: 9
# "set" x to 4 with a function call
In [9]: f2 = g(4)
In [10]: f2(2)
Out[10]: 16
# What happens when we call the first function now?
In [11]: f1(2)