×

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

Python Abstract Class

An Introduction to Abstract Classes An Abstract Class is one of the most significant concepts of Object-Oriented Programming (OOP). An Abstract class can be deliberated as a blueprint or design for...

6 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 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.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python Selectors

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

4 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.