global Statements
Defining the global Statements
In Python, the ‘global’ keyword is used to declare that a variable is a global variable. That is, it’s not just limited in scope to the function it’s used in, but it can be accessed from anywhere in the program. By default, all variables declared inside a function are local, and can’t be accessed outside the function. The ‘global’ keyword changes this behaviour.
This will output:
Initially, x
is a global variable with a value of 20
. However, when my_function
is called, we declare a global x
, which is a different variable, and set its value to 10
. This changes the value of x
globally, hence the x
printed after the function call is 10
, not 20
.
Caution
Misuse of the ‘global’ keyword can lead to code that’s difficult to understand and debug, as it breaks the locality principle. Use it sparingly!
Working with multiple global variables
The ‘global’ keyword isn’t limited to one variable per function. You can declare multiple global variables in the same function:
This will output:
Same as before, the global variable x
and y
change their values globally when my_function
is called.
The ‘global’ keyword can help you modify global variables from within functions and manage variable scope. While it can be useful, be careful not to overuse it, as it can make your code harder to understand.
Note
Remember, by default, variables declared in a function are local to that function. To access them outside that function, you must declare them as global.