Merry Christmas my dear network. Ready for some Python on Christmas day? Here we go.
At the risk of kicking in open doors: don’t confuse the semantics of variable declaration in for-loops with functions.
Variables that are defined in a function, are local to that function. They exist in the so called “local scope” of the function and are not accessible outside of that function (unless you define the variable to be global, but let’s skip over that for the sake of keeping this post short).
Variables that are defined in a for-loop áre accessible outside of the for-loop.
Details and an example of this can be found below.
# Variables defined within a for loop are still accessible after the loop ends
# The same is not true for functions. In a function variables are defined in a "local scope" (only available inside the function). "Local variables" are not accessible in the "global scope" (outside of the function)
# Creating a loop with variables "z" and "f"
for z in range(5):
f = z+1
# Creating a function with variable "woorden" (local scope)
def name_function(name: str):
woorden = 'Your name is '
return print(f'{woorden}{name}')
# Using variables defined in the loop, outside the loop
print(z) # Variable accessible outside of for loop; returns 4
print(f) # Variable accessible outside of for loop; returns 5
# Executing name_function
name_function('David') # Returns "Your name is David"
# Trying to access local variable "woorden" from name_function
try:
print(woorden) # This throws an error saying the variable is not defined
except NameError as e:
print(f'NameError occurred: {e}.') # Which results in this line being executed