Skip to content

Python global keyword | Change scope of variables

  • by

Python global keyword is used to change the scope of variables. By default variables inside the function has local scope. Means you can’t use it outside the function.

Simple use global keyword to read and write a global variable inside a function.

Note: If a variable defines outside the function it is global by default. You don’t have to use global keyword.

Example use of global keyword in Python

A simple example code declares a global variable inside a function and uses it outside the function. Here is how to create global variables from a no-global scope and print the value.

# Create a function:
def my_func():
    global var
    var = "My function variable"


# Execute the function:
my_func()

# access global variable outside function 
print(var)

Output:

Python global keyword example

Without global keyword in variable

Let’s try the access a function variable outside the function scope.

def my_func():
    var = "My function variable"


my_func()

# access variable outside function
print(var)

Output: NameError: name ‘var’ is not defined

Global and Local Variable with the same name

It is possible to have a global and local variable with the same name.

# global variable
s = "Global Variable"


def func():
    # local variable
    s = "Local Variable"
    print("I am a " + s)


func()
print("I am a " + s)

Output:

I am a Local Variable
I am a Global Variable

Do comment if you have any doubts or suggestions on this Python keywords tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *