Control Flow: The for
Loops
Block Scoping
Variables are not accessible outside the function block they are defined in. The variable is also accessible in the inner blocks of the function. A variable is also not accessible before it is defined in an earlier line of code.
variable1 = 1
print("variable1 is ", variable1, " initially")
def function1():
# variable1 is accessible in this block of the function as well
print("variable1 is ", variable1, " inside the function block")
variable2 = 2
# variable2 is accessible in this block of the function and the inner blocks
global variable3
variable = 3
# variable3 will be accessible to the global scope as soon as the function1() is called for the first time
for _ in range(5):
# Both variable1 and variable2 as well as variable3 are accessible in this inner block
print("variable1 is ", variable1, " inside the for loop block")
print("variable2 is ", variable2, " inside the for loop block")
variable3 = 3
print("variable3 is ", variable3)
variable3 += 1
print("variable3 is ", variable3, " after the increment")
# The loop counter or iteration variable _ is accessible throughout
# the entire cycles of the for loop without losing its current value
print("This was the iteration ", _, " of the for loop\n")
# variable1 and variable2 are still accessible
print("variable1 is ", variable1, " outside of the for loop block")
print("variable2 is ", variable2, " outside of the for loop block")
# making a call to the function1()
function1()
# variable2 is not accessible outside the block scope of the function1
# uncomment the next line by removing the "#" to see the effect
# print(variable2)
# variable3 is accessible to the global scope once the function1() is called
print("variable3 is ", variable3, " finally")
# variable1 is still accessible in this scope, as it is defined in the outer code block
print("variable1 is ", variable1, " finally")