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.

1def my_function():
2    global x
3    x = 10
4    print("Value inside function:",x)
5
6x = 20
7my_function()
8print("Value outside function:",x)

This will output:

Value inside function: 10
Value outside function: 10

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:

 1def my_function():
 2    global x, y
 3    x = 10
 4    y = 30
 5    print("Values inside function:",x, y)
 6
 7x = 20
 8y = 40
 9my_function()
10print("Values outside function:",x, y)

This will output:

Values inside function: 10 30
Values outside function: 10 30

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.