What are global variables in Python?

If I create a global variable in one function, how can I use that variable in another function?

We can create a global with the following function:

def create_global_variable(): global global_variable # must declare it to be a global first # modifications are thus reflected on the module's global scope global_variable = 'Foo'

Writing a function does not actually run its code. So we call the create_global_variable function:

>>> create_global_variable()

Using globals without modification

You can just use it, so long as you don't expect to change which object it points to:

For example,

def use_global_variable(): return global_variable + '!!!'

and now we can use the global variable:

>>> use_global_variable() 'Foo!!!'

Modification of the global variable from inside a function

To point the global variable at a different object, you are required to use the global keyword again:

def change_global_variable(): global global_variable global_variable = 'Bar'

Note that after writing this function, the code actually changing it has still not run:

>>> use_global_variable() 'Foo!!!'

So after calling the function:

>>> change_global_variable()

we can see that the global variable has been changed. The global_variable name now points to 'Bar':

>>> use_global_variable() 'Bar!!!'

Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables.

Local variables with the same name

If you create a local variable with the same name, it will overshadow a global variable:

def use_local_with_same_name_as_global(): # bad name for a local variable, though. global_variable = 'Baz' return global_variable + '!!!' >>> use_local_with_same_name_as_global() 'Baz!!!'

But using that misnamed local variable does not change the global variable:

>>> use_global_variable() 'Bar!!!'

Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.

We get the same behavior in classes

A follow on comment asks:

what to do if I want to create a global variable inside a function inside a class and want to use that variable inside another function inside another class?

Here I demonstrate we get the same behavior in methods as we do in regular functions:

class Foo: def foo(self): global global_variable global_variable = 'Foo' class Bar: def bar(self): return global_variable + '!!!' Foo().foo()

And now:

>>> Bar().bar() 'Foo!!!'

But I would suggest instead of using global variables you use class attributes, to avoid cluttering the module namespace. Also note we don't use self arguments here - these could be class methods (handy if mutating the class attribute from the usual cls argument) or static methods (no self or cls).

In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.

Here's an example of a global variable:

x = 10 def showX(): print("The value of x is", x) showX() # The value of x is 10

The variable x in the code above was declared outside a function: x = 10.

Using the showX() function, we were still able to access x because it was declared in a global scope.

Let's take a look at another example that shows what happens when we declare a variable inside a function and try to access it elsewhere.

def X(): x = 10 X() def showX(): print("The value of x is", x) showX() NameError: name 'x' is not defined

In the example above, we declared x inside a function and tried to access it in another function. This resulted in a NameError because x was not defined globally.

Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared.

You can change the scope of a local variable using the global keyword – which we'll discuss in the next section.

What is the global Keyword Used for in Python?

The global keyword is mostly used for two reasons:

  • To modify the value of a global variable.
  • To make a local variable accessible outside the local scope.

Let's look at some examples for each scenario to help you understand better.

Example #1 - Modifying a Global Variable Using the global Keyword

In the last section where we declared a global variable, we did not try to change the value of the variable. All we did was access and print its value in a function.

Let's try and change the value of a global variable and see what happens:

x = 10 def showX(): x = x + 2 print("The value of x is", x) showX() # local variable 'x' referenced before assignment

As you can see above, when we tried to add 2 to the value of x, we got an error. This is because we can only access but not modify x.

To fix that, we use the global variable. Here's how:

x = 10 def showX(): global x x = x + 2 print("The value of x is", x) showX() # The value of x is 12

Using the global keyword in the code above, we were able to modify x and add 2 to its initial value.

Example #2 - How to Make a Local Variable Accessible Outside the Local Scope Using the global Keyword

When we created a variable inside a function, it wasn't possible to use its value inside another function because the compiler did not recognize the variable.

Here's how we can fix that using the global keyword:

def X(): global x x = 10 X() def showX(): print("The value of x is", x) showX() # The value of x is 10

To make it possible for x to be accessible outside its local scope, we declared it using the global keyword: global x.

After that, we assigned a value to x. We then called the function we used to declare it: X()

When we called the showX() function, which prints the value of x declared in the X() function, we did not get an error because x has a global scope.

Summary

In this article, we talked about global and local variables in Python.

The examples showed how to declare both global and local variables.

We also talked about the global keyword which lets you modify the value of a global variable or make a local variable accessible outside its scope.

Happy coding!

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What are global variables with examples?

Global variables are those variables which are declared outside of all the functions or block and can be accessed globally in a program. It can be accessed by any function present in the program..
#include<stdio. h>.
int a=50, b=40;.
void main().
printf("a = %d and b=%d",a,b);.

What are local and global variables in Python?

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

What is meant by global variable?

The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.

What is global used for in Python?

In Python, the global keyword allows us to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Chủ đề