The Wayback Machine - https://web.archive.org/web/20240602033439/https://www.geeksforgeeks.org/global-local-variables-python//
Open In App

Global and Local Variables in Python

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas the global variables are accessible throughout the program and inside every function. 

Python Local Variables

Local variables in Python are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable.

Creating local variables in Python

Defining and accessing local variables

Python3




def f():
 
    # local variable
    s = "I love Geeksforgeeks"
    print(s)
 
 
# Driver code
f()


Output

I love Geeksforgeeks

Can a local variable be used outside a function?

If we will try to use this local variable outside the function then let’s see what will happen.

Python3




def f():
     
    # local variable
    s = "I love Geeksforgeeks"
    print("Inside Function:", s)
 
# Driver code
f()
print(s)


Output:

NameError: name 's' is not defined

Python Global Variables

These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a Python global variable.

Create a global variable  in Python

Defining and accessing Python global variables.

Python3




# This function uses global variable s
def f():
    print("Inside Function", s)
 
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)


Output

Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks

The variable s is defined as the global variable and is used both inside the function as well as outside the function.

Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name.

Why do we use Local and Global variables in Python?

Now, what if there is a Python variable with the same name initialized inside a function as well as globally? Now the question arises, will the local variable will have some effect on the global variable or vice versa, and what will happen if we change the value of a variable inside of the function f()? Will it affect the globals as well? We test it in the following piece of code: 

Example

If a variable with the same name is defined inside the scope of the function as well then it will print the value given inside the function only and not the global value. 

Python3




# This function has a variable with
# name same as s.
def f():
    s = "Me too."
    print(s)
 
# Global scope
s = "I love Geeksforgeeks"
f()
print(s)


Output

Me too.
I love Geeksforgeeks

Now, what if we try to change the value of a global variable inside the function? Let’s see it using the below example.

Python3




# This function uses global variable s
def f():
    s += 'GFG'
    print("Inside Function", s)
 
 
# Global scope
s = "I love Geeksforgeeks"
f()


Output:

UnboundLocalError: local variable 's' referenced before assignment

To make the above program work, we need to use the “global” keyword in Python. Let’s see what this global keyword is.

The global Keyword

We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for printing and accessing. Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first statement throws the error message. Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example: 

Example 1: Using Python global keyword

Python3




# This function modifies the global variable 's'
def f():
    global s
    s += ' GFG'
    print(s)
    s = "Look for Geeksforgeeks Python Section"
    print(s)
 
# Global Scope
s = "Python is great!"
f()
print(s)


Output

Python is great! GFG
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section

Now there is no ambiguity. 

Example 2: Using Python global and local variables

Python3




a = 1
 
# Uses global because there is no local 'a'
def f():
    print('Inside f() : ', a)
 
# Variable 'a' is redefined as a local
def g():
    a = 2
    print('Inside g() : ', a)
 
# Uses global keyword to modify global 'a'
def h():
    global a
    a = 3
    print('Inside h() : ', a)
 
 
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)


Output

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3

Difference b/w Local Variable Vs. Global Variables

Comparision Basis Global Variable Local Variable
Definition declared outside the functions declared within the functions
Lifetime They are created  the execution of the program begins and are lost when the program is ended They are created when the function starts its execution and are lost when the function ends
Data Sharing Offers Data Sharing It doesn’t offers Data Sharing
Scope Can be access throughout the code Can access only inside the function
Parameters needed parameter passing is not necessary parameter passing is necessary
Storage  A fixed location selected by the compiler They are  kept on the stack
Value Once the value changes it is reflected throughout the code once changed the variable don’t affect other functions of the program


Previous Article
Next Article

Similar Reads

Python program to find number of local variables in a function
Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Implementation of above approach # A function contai
1 min read
Can Global Variables be dangerous ?
In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how. C/C++ Code // A C++ program to demonstrate that a // global variables make long code less // maintainable. int c = 1; int fun1()
2 min read
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python. What is the purpose of global keywords in python? A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is
5 min read
What is the Python Global Interpreter Lock (GIL)
Python Global Interpreter Lock (GIL) is a type of process lock which is used by python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. This means that in python only one thread will be executed at a time. The performance of the single-threaded process and the multi-threaded pro
5 min read
Use of nonlocal vs use of global keyword in Python
Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
Create Local Binary Pattern of an image using OpenCV-Python
In this article, we will discuss the image and how to find a binary pattern using the pixel value of the image. As we all know, image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the
5 min read
How to Scrape Data From Local HTML Files using Python?
BeautifulSoup module in Python allows us to scrape data from local HTML files. For some reason, website pages might get stored in a local (offline environment), and whenever in need, there may be requirements to get the data from them. Sometimes there may be a need to get data from multiple Locally stored HTML files too. Usually HTML files got the
4 min read
Requesting a URL from a local File in Python
Making requests over the internet is a common operation performed by most automated web applications. Whether a web scraper or a visitor tracker, such operations are performed by any program that makes requests over the internet. In this article, you will learn how to request a URL from a local File using Python. Requesting a URL from a local File
4 min read
Unused local variable in Python
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined. Example: C/C++ Code # simple display function def func(num): # local variable a = num print("The number is :", str(a)) func(10) # g
4 min read
How to parse local HTML file in Python?
Prerequisites: Beautifulsoup Parsing means dividing a file or input into pieces of information/data that can be stored for our personal use in the future. Sometimes, we need data from an existing file stored on our computers, parsing technique can be used in such cases. The parsing includes multiple techniques used to extract data from a file. The
5 min read
Article Tags :
Practice Tags :