How To Make A Local Variable Global In Python

In Python, variables are either local or global; a local variable is only visible within its function, while a global variable is visible throughout the entire program.

This tutorial will cover how to make a local variable global using the global keyword. We’ll discuss the importance of scope when dealing with variables and understand how to convert a local variable to a global variable.

What is the Global Keyword?

The global keyword in Python allows a variable to be accessed from anywhere in the code, making it global in scope. When a variable is declared within a function, it is local by default and is only accessible within that function. By placing the global keyword before a variable name, we indicate that the variable being declared is a global variable.

How to make a local variable global

Let’s follow these steps to understand how to make a local variable global in Python:

  1. Create a local variable inside a function
  2. Use the global keyword before the variable
  3. Access the global variable inside another function or outside of the function

Now let’s dive into an example to see the process in action.

The output of the above code will be:

10

Explanation

In the given example, we have two functions, my_function() and another_function(). The local variable my_var is created inside my_function() with the value of 10, and we use the global keyword to make it a global variable.

After defining both functions, we first call my_function(), which not only sets the value of my_var to 10 but also makes it a global variable.

Then, we call another_function() which prints the value of the global variable my_var. Since my_var is now accessible outside of my_function(), we are able to access and print its value from within another_function().

Full Code

Conclusion

Understanding the scope of variables and the usage of the global keyword in Python is essential to prevent issues related to variable accessibility. By following the steps provided, you can easily convert a local variable to a global variable and access it from different parts of your code. Keep in mind, however, that excessive usage of global variables can lead to potential issues in the long run, so use them judiciously and only if absolutely necessary.