×

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

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.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

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

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.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

How to create a DataFrames in Python

How to create a DataFrames in Python Data Frame is a data structure in which data is stored in tabular form. They can also be referred as two-dimensional collection of data. Various...

5 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

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

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Python math.cos and math.acos function

Math.cos() function In Python, the Math module is used for performing the mathematical operations. It includes the math.cos() function that is used for obtaining the cosine value of an angle in...

3 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.