×

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

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Python Banner

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

GUI Calendar 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...

3 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

EDA in Python

The EDA is the exploratory data analysis; the data scientists mainly use the EDA to understand the main features of the data quickly, the variables in python and the relationship...

6 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

4 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.