Texts: 1. Variable Scope. A variable is visible from its definition in a block up to the end of the block. Any variables defined inside of a block are not visible outside of the block. Variables declared inside of a function, including both parameters and local variables, are only visible inside of the function.
Scope.py (click to download)
def fun1(c): # Line 1
b = 5 # Line 2
d = 3 # Line 3
print(c) # Line 4
print(d) # Line 5
print(a) # Line 6
print(b) # Line 7
a = 2 # Line 8
b = 7 # Line 9
if a == 0: # Line 10
b = 1 # Line 11
fun1(b) # Line 12
print(b) # Line 13
For each line number and variable combination listed below, determine if the variable is in global or local scope at that line number. Check your answers below.
Line 1, variable c
Line 2, variable b
Line 3, variable d
Line 4, variable c
Line 6, variable a
Line 7, variable b
Line 8, variable a
Line 12, variable b
1.1. What is the scope?
1.1.1 What is the scope of the variable c at Line 1?
1.1.2 What is the scope of the variable b at Line 2?
1.1.3 What is the scope of the variable d at Line 3?
1.1.4 What is the scope of the variable c at Line 4?
1.1.5 What is the scope of the variable a at Line 6?
1.1.6 What is the scope of the variable b at Line 7?
1.1.7 What is the scope of the variable a at Line 8?
1.1.8 What is the scope of the variable b at Line 12?