forked from bloominstituteoftechnology/Intro-Python-I
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscope.py
More file actions
32 lines (21 loc) · 748 Bytes
/
Copy pathscope.py
File metadata and controls
32 lines (21 loc) · 748 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Experiment with scope in Python.
# Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables
# When you use a variable in a function, it's local in scope to the function.
x = 12
def changeX():
global x # <-- Tell Python to use x in the global scope
x = 99
changeX()
# This prints 12. What do we have to modify in changeX() to get it to print 99?
print(x)
# This nested function has a similar problem.
def outer():
y = 120
def inner():
nonlocal y # <-- Tell Python to use y from the containing scope
y = 999
inner()
# This prints 120. What do we have to change in inner() to get it to print
# 999? Google "python nested function scope".
print(y)
outer()