How To Declare A Global Variable In Python

In Python, global variables are variables that can be accessed from any part of the code, regardless of scope. This means that they can be used by any function inside the Python file, without needing to be passed as arguments. In this tutorial, we will discuss how to declare global variables in Python and how to access them in different functions.

Step 1: Declare a Global Variable

Declaring a global variable in Python is quite simple. Just define a variable outside any function, usually at the top of your code. For example, let’s define a global variable x with an initial value of 0.

Now, this variable x can be accessed and modified by any function present in your code.

Step 2: Access Global Variable Inside a Function

To access the global variable inside a function, simply reference it by its name as you would with any other variable. Let’s create a function called print_global_var that prints the value of the global variable x.

Now let’s call this function:

The output will be:

The value of the global variable x is: 0

Step 3: Modify Global Variable Inside a Function

If you want to modify the value of a global variable inside a function, you need to declare it as global inside the function. This is done using the global keyword followed by the variable name.

Let’s create a function called increment_global_var that increments the value of the global variable x by 1.

Now let’s call this function and then call print_global_var again:

The output will be:

The value of the global variable x is: 1

The value of the global variable x has been changed to 1.

Now let’s look at the full code:

Running this code will produce the following output:

The value of the global variable x is: 0
The value of the global variable x is: 1

Conclusion

In this tutorial, we learned how to declare a global variable in Python, how to access it inside a function, and how to modify its value using the global keyword. Global variables can be very useful for sharing information between various functions and parts of your code, but they should be used sparingly and carefully to avoid making the code hard to understand and maintain.