global statement in Python
Let us have an external global variable i. We also have a function func that adds one to this variable:
i = 0
def func():
i += 1 # an error return i
After executing the code, an error will be returned because there is a conflict between the global i declared in the external code and the local i, to which 1 is added, but the variable itself has not yet been declared. In order to fix this problem and set the function to work with the global variable, you need to use the global instruction. This instruction is a declaration that is executed for the entire current block of code in which it is defined.
Let's rewrite the previous example by declaring global in the function body:
def func():
global i
i += 1
return i
print(func()) # 1
In the following code, some programmer made a mistake:
num = 4
def func():
num *= 2
return num
print(func())
What's wrong with this code? Find and fix the code author's mistake.
In the following code, some programmer made a mistake:
num = 10
def func():
num -= 3
return i
print(func())
What's wrong with this code? Find and fix the code author's mistake.