Python class global and local variables

Global Variables

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

Let's see an example of how a global variable is created in Python.

Example 1: Create a Global Variable

x = "global"

def foo():
    print("x inside:", x)


foo()
print("x outside:", x)

Output

x inside: global
x outside: global

In the above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change the value of x inside a function?

x = "global"

def foo():
    x = x * 2
    print(x)

foo()

Output

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work, we use the global keyword. Visit Python Global Keyword to learn more.


Local Variables

A variable declared inside the function's body or in the local scope is known as a local variable.

Example 2: Accessing local variable outside the scope

def foo():
    y = "local"


foo()
print(y)

Output

NameError: name 'y' is not defined

The output shows an error because we are trying to access a local variable y in a global scope whereas the local variable only works inside foo() or local scope.


Let's see an example on how a local variable is created in Python.

Example 3: Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

def foo():
    y = "local"
    print(y)

foo()

Output

local

Let's take a look at the earlier problem where x was a global variable and we wanted to modify x inside foo().


Global and local variables

Here, we will show how to use global variables and local variables in the same code.

Example 4: Using Global and Local variables in the same code

x = "global "

def foo():
    global x
    y = "local"
    x = x * 2
    print(x)
    print(y)

foo()

Output

global global 
local

In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.

After calling the foo(), the value of x becomes global global because we used the x * 2 to print two times global. After that, we print the value of local variable y i.e local.


Example 5: Global variable and Local variable with same name

x = 5

def foo():
    x = 10
    print("local x:", x)


foo()
print("global x:", x)

Output

local x: 10
global x: 5

In the above code, we used the same name x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().

When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the variable.

Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the global scope of the variable.


Nonlocal Variables

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

Let's see an example of how a nonlocal variable is used in Python.

We use nonlocal keywords to create nonlocal variables.

Example 6: Create a nonlocal variable

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)


outer()

Output

inner: nonlocal
outer: nonlocal

In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().

Note : If we change the value of a nonlocal variable, the changes appear in the local variable.

Global variables are those which are not defined inside any function and have a global scope whereas local variables are those which are defined inside a function and its scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas the global variables are accessible throughout the program and inside every function. Local variables are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable.

Example: Creating local variables

Python3

def f():

    s = "I love Geeksforgeeks"

    print(s)

f()

Output

I love Geeksforgeeks

If we will try to use this local variable outside the function then let’s see what will happen.

Example:

Python3

def f():

    s = "I love Geeksforgeeks"

    print("Inside Function:", s)

f()

print(s)

Output:

NameError: name 's' is not defined

Global Variables

These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a global variable.

Example: Defining and accessing global variables

Python3

def f():

    print("Inside Function", s)

s = "I love Geeksforgeeks"

f()

print("Outside Function", s)

Output

Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks

The variable s is defined as the global variable and is used both inside the function as well as outside the function.

Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name.

Now, what if there is a variable with the same name initialized inside a function as well as globally. Now the question arises, will the local variable will have some effect on the global variable or vice versa, and what will happen if we change the value of a variable inside of the function f()? Will it affect the globals as well? We test it in the following piece of code: 

Python3

def f():

    s = "Me too."

    print(s)

s = "I love Geeksforgeeks"

f()

print(s)

Output

Me too.
I love Geeksforgeeks

If a variable with the same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value. 

The question is, what if we try to change the value of a global variable inside the function. Let’s see it using the below example.

Example: 

Python3

def f():

    s += 'GFG'

    print("Inside Function", s)

s = "I love Geeksforgeeks"

f()

Output:

UnboundLocalError: local variable 's' referenced before assignment

To make the above program work, we need to use the “global” keyword. Let’s see what this global keyword is.

Global Keyword:

We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for printing and accessing. Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first statement throws the error message. Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example: 

Example 1: Using global keyword

Python3

def f():

    global s

    s += ' GFG'

    print(s)

    s = "Look for Geeksforgeeks Python Section"

    print(s) 

s = "Python is great!" 

f()

print(s)

Output

Python is great! GFG
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section

Now there is no ambiguity. 

Example 2: Using global and local variables

Python3

a = 1

def f():

    print('Inside f() : ', a)

def g():

    a = 2

    print('Inside g() : ', a)

def h():

    global a

    a = 3

    print('Inside h() : ', a)

print('global : ', a)

f()

print('global : ', a)

g()

print('global : ', a)

h()

print('global : ', a)

Output

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3

This article is contributed by Shwetanshu Rohatgi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


Can class use global variable Python?

You can create a variable with global scope by initializing outside all the functions in a python program. And you can access the variable from anywhere in the python program. ... How to Use Global Keywords in Python With Examples?.

Does Python have global and local variables?

Practical Data Science using Python There are two types of variables: global variables and local variables. The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined.

How do you declare a global variable in a class Python?

We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.

Should you avoid using global variables in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.