Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Python Global Variables

Uploaded by

omkarinfotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Python Global Variables

Uploaded by

omkarinfotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

pynative.

com /python-global-variables/

Python Global Variables


⋮ 10/21/2022

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

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.

1/9
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()

2/9
# 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()

3/9
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

4/9
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

5/9
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

6/9
# 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.

7/9
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

8/9
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

9/9

You might also like