PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Python Global Variables

Python Global Variables

Updated on: October 21, 2022 | 1 Comment

In this tutorial, you’ll learn what is a global variable in Python and how to use them effectively.

Goals of this lesson:

  • Understand what is a global variable in Python with examples
  • Use global variables across multiple functions
  • Learn how to use the global keyword to modify the global variables
  • Learn to use global variables across Python modules/files
  • Understand the use of globals() function
  • Use global variables inside a nested function

Table of contents

  • What is a Global Variable in Python
  • Using Global Variables In Function
    • Global Variable and Local Variable with Same Name
  • global Keyword in Python
    • Modify a global variable inside a function
    • Create a global variable inside a function
    • Rules of global keyword
  • Global Variables Across Python Modules/Files
  • globals() function in Python
  • Global variables in Nested Function

What is a Global Variable in Python

In Python, a variable declared outside the function or in global scope is known as a global variable. We can use global variables both inside and outside the function.

The scope of a global variable is broad. It is accessible in all functions of the same module.

Python global variables
Python global variables

Let’s understand it with an example.

Example:

In this example, we declared a global variable name with the value ‘Jessa’. The same global variable name is accessible to everyone, both inside of functions and outside.

# global variable
name = 'Jessa'

def my_func():
    # access global variable inside function
    print("Name inside function:", name)

my_func()

# access global variable outside function
print('Name Outside function:', name)Code language: Python (python)

Output:

Name inside function: Jessa
Name Outside function: Jessa

Using Global Variables In Function

We can use global variables across multiple functions of the same module.

Now, let’s see how to use the global variable inside a Python function.

  • First, create a global variable x and initialize it to 20. The same global variable x is accessible to everyone, both inside of functions and outside.
  • Now, create a function with a combination of local variables and global variables.
  • Create a local variable y And initialize it to 30. A local variable is declared inside the function and is not accessible from outside it. The local variable’s scope is limited to that function only where it is declared.
  • In the end, add a global variable x and local variable y to calculate the sum of two variables.

Example:

# global variable
x = 20

def add():
    # local variable y
    y = 30
    print('local variable y=', y)

    # Use global variable x
    print('global variable x=', x)
    z = x + y
    print('x+y=', z)

def sub():
    # local variable m
    m = 10
    print('local variable m=', m)

    # Use global variable x in second function
    print('global variable x=', x)
    n = x - m
    print('x-m=', n)

add()
sub()Code language: Python (python)

Output:

local variable y= 30
global variable x= 20
x+y= 50

local variable m= 10
global variable x= 20
x-m= 10

Global Variable and Local Variable with Same Name

Note: If you create a new local variable inside a function with the same name as a global variable, it will not override the value of a global variable. Instead, the new variable will be local and can only be used inside the function. The global variable with the same name will remain unchanged.

Example:

# global variable
x = 20

def my_func():
    # local variable with same name
    # it will not change global variable x
    x = 50
    print('local variable x=', x)

    # modify local variable x
    x = 100
    print('local variable x=', x)

my_func()
print('Global variable x=', x)
Code language: Python (python)

Output:

local variable x= 50
local variable x= 100
Global variable x= 20

global Keyword in Python

The global keyword is used in the following two cases.

  • To access and modify a global variable inside a function
  • To create a new global variable inside a function

Modify a global variable inside a function

let’s see the below code.

# global variable
x = 20

def my_func():
    # modify global variable x
    x = x + 30

my_func()Code language: Python (python)

Output:

UnboundLocalError: local variable 'x' referenced before assignment

Execute the above code to change the global variable x’s value. You’ll get an UnboundLocalError because Python treats x as a local variable, and x is also not defined inside my_func(). i.e, You cannot change or reassign value to a global variable inside a function just like this.

Use the global keyword to change the value of a global variable inside a function.

Example:

# global variable
x = 20

def my_func():
    # modify global variable x using global keyword
    global x
    x = x + 30
    print('global variable x inside a function:', x)

# Value of global variable before calling a function
print('global variable x outside a function:', x)

# Value of global variable after calling a function
my_func()
print('global variable x outside a function:', x)Code language: Python (python)

Output:

global variable x outside a function: 20
global variable x inside a function: 50
global variable x outside a function: 50

Create a global variable inside a function

in Python, the scope of variables created inside a function is limited to that function. We cannot access the local variables from outside of the function. Because the scope is local, those variables are not visible outside the function.

To overcome this limitation, we can use the global keyword to create a global variable inside a function. This global variable is accessible within and outside the function.

Example:

def my_func():
    # create new global variable x using global keyword
    global x
    x = 100
    print('global variable x inside a function:', x)

my_func()
print('global variable x outside a function:', x)Code language: Python (python)

Output:

global variable x inside a function: 100
global variable x outside a function: 100

Rules of global keyword

Let us see the rules we need to follow to create and use a global keyword.

  • If we create a variable inside a function, it is a local variable by default.
  • If we create a variable outside the function, it turns into a global variable, and we don’t have to use the keyword global.
  • We use the keyword global to create a global variable inside a function or to change a global variable already declared outside the function.
  • Using the global keyword outside the function does not make any difference.

Global Variables Across Python Modules/Files

By default, the global variables are accessible across multiple functions of the same module. Now, we’ll see how to share global variables across the modules.

  • First, create a special module config.py and create global variables in it.
  • Now, import the config module in all application modules, then the module becomes available for a global name.

Let us understand it using an example.

In Python, to create a module, write Python code in the file, and save that file with the .py extension.

Example: Share global variables across Python modules.

config.py: The config module stores global variables of school and grade

# global variables

company_name = 'ABC Company'
address = 'XYZ street, New York'Code language: Python (python)

Now, run the config.py file.

company.py: create a company.py file to import global variables and modify them. In the company.py file, we import the config.py module and modify the values of the name and address.

# load config module
import config

# modify global variables
config.company_name = 'ABC Tech'
config.address = "New Street, california"
Code language: Python (python)

Now, run the company.py file.

employee.py:

Now, in the employee file, we import both config and company modules to test the values of global variables and whether they are changed.

# load config and company module
import config
import company

print('Company Name:', config.company_name)
print('Address:', config.address)Code language: Python (python)

Output:

Company Name: ABC Tech
Address: New Street, california

As you can see in the output, we successfully accessed and modified the global variables across the files or modules.

globals() function in Python

In this section, we’ll see what the globals() do in Python.

We can also use the globals() function to access and modify the global variables. The globals() function returns the dictionary of the current global symbol table.

The global symbol table stores all information related to the program’s global scope and is accessed using the globals() method.

Function and variables are not part of any class, or functions are stored in a global symbol table.

Example: Modify the global variable using the globals() function.

# global variable
z = 20

def add():
    x = 30
    y = 20

    # change value of global variable using globals()
    globals()['z'] = x + y

print('Global variable before calling function:', z)
add()

print('Global variable after calling function:', z)Code language: Python (python)

Output:

Global variable before calling function: 20
Global variable after calling function: 50

Global variables in Nested Function

Now, Let’s see how to use a global variable in a nested function. Global variables can be used in a nested function using global or nonlocal keywords.

The difference between nonlocal and global is that global is used to change global variables, while nonlocal is used to change variables outside the function. Let us illustrate this with an example.

Example: Access global variables in nested functions using the global keyword

# global variable
a = 10

def outer_fun():
    b = 20

    def inner_fun():
        c = 30
        # access outer function variable using nonlocal
        nonlocal b

        # access global variable using global
        global a

        # add them
        a = b + c
    
    # call inner function
    inner_fun()

print('Global variable before calling nested function:', a)
outer_fun()

print('Global variable after calling nested function:', a)
Code language: Python (python)

Output:

Global variable before calling nested function: 10
Global variable after calling nested function: 50

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement