Local scope of variables in Python
All variables inside a function have a so-called local scope - They are only accessible within their function and cannot be accessed by external code.
Let's say we have a function that contains a variable num:
def func():
num = 2
return num
Let's call it and try to print the variable num to the console. After executing the code, an error will be returned because the variable is unknown in the external code:
func()
print(num) # will display an error
What will be the result of running the following code:
def func():
num = 1
func()
print(num)
What will be the result of running the following code:
def func():
num = 3
print(num)
func()
What will be the result of running the following code:
def func():
num = 5
return num
print(func())
What will be the result of running the following code:
def func():
num = 7
return num
func()
print(num)