+ 2

What does global do in python?

Can someone explain me what global does and can you give me a code as an example.

8th Aug 2018, 2:51 PM
Shuaib Nuruddin
Shuaib Nuruddin - avatar
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.
8th Aug 2018, 3:54 PM
Sondre Watnedal
Sondre Watnedal - avatar
+ 2
Sondre Watnedal Thanks
9th Aug 2018, 8:15 AM
Shuaib Nuruddin
Shuaib Nuruddin - avatar