×

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples.

Any variable holds a value in it. Depending on the place, the variable is declared in the program, and the variable can either hold the value until the end of the program or hold only until the end of a particular block. This is the differentiation between global and local variables.

A variable that is not defined inside a function and can hold its value till the end of the program, and can be accessed anywhere is called a global variable. On the other hand, the variable that is defined inside a particular function and can hold their values in that function block only are called local variables.

Once initialized, a global variable can be accessed throughout the program, even inside functions.

  • Let us take an example:

In the following code:

def function ():
    s = "Local variable"
    print (s)
function ()

Output:

Local variable

We defined a variable s inside the function and accessed it. Hence, we were able to access it. If we try to access it outside the function:

def function ():
    s = "Local variable" //Local variable
    print (s)
function ()
print (s)

Output:

NameError: name 's' is not defined

Here, s is a local variable. Hence, its scope is permitted only to the function block.

  • Let us now take an example of a global variable:
s = "Local variable" //Global variable
def function ():
    print (s)
function ()
print (s)

Output:

Local variable
Local variable

Here, s is defined globally and not inside any particular code block. Hence, when we tried to access the value of s inside the function and outside the function, we could access it.

  • Now, you might be wondering what if we declare a global variable and a local variable with the same name. What will happen if we modify the value of the local variable? Which value will be displayed when we try to access the variable inside the function?

Let’s see with this example:

s = "Global variable"
def function ():
    s = "Local variable"
    print (s)
function ()
print(s)

Output:

Local variable
Global variable

Understanding:

As you can observe in the program, a local variable dominates the global variable inside a function. Hence, when we tried to access s inside the function, the local variable s is accessed and not the global variable s.

  • Now, say that we have a global variable s. We want to modify its value by writing a function. Can we do that? Let us see:
s = "Global variable"
def function ():
    s = "I am a" + s
    print (s)
function ()

Output:

UnboundLocalError: local variable 's' referenced before assignment

Understanding:

As discussed earlier, inside a function local variable dominates the global variable. Hence, in the above code, when we tried to modify the global variable inside the function, the variable is considered as a local variable. An error is raised asking us to define it first before modifying it. This problem occurs only when we need to assign or change the variable.

So, we need to let the interpreter know that we need to modify the global variable inside the function. But, how do we do that?

Global Keyword:

We need to mention the global keyword before the variable name to let the interpreter know that we talk about the global variable and not the local variable.

Let us take an example:

s = "Global variable"
def function ():
    global s
    s = "I am a " + s
    print (s)
    s = "Assigning a new value"
function ()
print (s)

Output:

I am a Global variable
Assigning a new value

Understanding:

In the above program, we declared a global variable s. We wrote a function in which we wanted to add I am a to s. To modify s, a global variable, we used the global keyword to let the interpreter know. Then, we concatenated "I am a "to s and printed it. This way, we modified the global variable inside a function. We changed it as s is declared as a global variable already. When we printed the value of s outside the function, we got the changed value as the output.

Program for clarity:

//Simple global variable
s = "Global variable"
def function ():
    print (s)
function ()
print (s)


//simple local variable
def function1 ():
    s = "Local variable"
    print (s)
function1 ()


//modifying a global variable
t = "global variable"
def function2 ():
    global t
    t = "I am a " + t
    print (t)
function2 ()
print (t)

Output:

Global variable
Global variable
Local variable
I am a global variable
I am a global variable

Related Topics

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Compound Interest GUI Calculator using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.