+ 2
What does global do in python?
Can someone explain me what global does and can you give me a code as an example.
2 odpowiedzi
+ 4
global declares variables as being global. This means that the data of the variable can be accessed outside of where it was defined.
Example:
def myFunc()
a = 4
myFunc()
print(a)
This will raise an exception, because the function does not share its declared variables, even after being called. With global we can fix this.
Here is the code again using global:
def myFunc()
global a
a = 4
myFunc()
print(a)
Now the program returns 4, because the function was told to make the variable a global, meaning that it is declared everywhere.
+ 2
Sondre Watnedal
Thanks