Day 26 - Scoping in Python
Skills: 7
Pre-reading: 13.1.1 (NOTE: references "the heap", which we haven't covered yet).
Intro (15 mins)
- Today we explore how variable assignment, mutability, and scoping work in Pyret and Python.
Pyret: Mutable vs Immutable
x = 10
# Can't do this, x is immutable
# x := 20 # Error!
var y = 5
y := y + 2 # y is now 7
# Can't re-declare a name in the same scope:
# y = 20 # Error!
Python: Assignment and Scoping
x = 10
x = 20 # x is now 20 -- all variables are mutable
y = 5
y = y + 2 # y is now 7
# Scoping example:
y = 20
def f():
y = 30 # This is a new local y, does not affect global y
return y
print(f()) # prints 30
print(y) # prints 20
# Using global keyword:
z = 100
def g():
global z # Now `z` within function is same as `z` at top level
z = 200
g()
print(z) # prints 200
Class Exercises (40 mins)
-
Given this Python code, predict what will happen and explain why:
y = 100
def outer():
y = 200
def inner():
y = y + 50
return y
return inner()
print(outer())Can you fix the code so that
inner()updates theyfromouter()? -
Given this Pyret code, predict what will happen and explain why:
x = 10
fun f() block:
x := x + 5
x
end
f()Now fix the code so that
f()updatesxcorrectly. -
Given this Python code, predict what will print and explain why:
x = 10
def foo():
x = x + 1
return x
print(foo())Now fix the above code so that it increments the global
x. -
Given this Pyret code, predict what will happen and explain why:
var a = 10
fun inc() block:
a := a + 1
a
end
inc()
a -
In the previous problem, what happens if you try to use
a = 20after declaringvar a = 10in Pyret? Why? -
If you get here and still have time, and didn't do all the exercises from Day 25, work on more of them!
Wrap-up (5 mins)
- Pyret and Python handle assignment, mutability, and scoping differently.
- Understanding these differences helps avoid bugs and write clearer code.