One way of introducing potential bugs is the lack of information about the way scopes work inside functions in Python.
When we declare global variables, their value may not change as we may expect.
Let us see this in an example to understand how a simple example can be misleading and confusing for a lot of people.
Let us assume that we have a global string called string
and we want to modify its value inside the scope of a method:
string = "string"
def do_nothing():
string = "inside a method"
print(string)
Now, if we want to call this function do_nothing(), we are going to get the same value as before for the string
value:
string = "string"
def do_nothing():
string = "inside a method"
print(string)
do_nothing() # inside a method
print(string) # string
If we want to change the value of string
, we need to use the access modifier global:
You need to use the access modifier global as well:
string = "string"
def do_nothing():
global string
string = "inside a method"
print(string)
do_nothing() # inside a method
print(string) # inside a method
a