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

Global and Local Variables in Python

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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

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

Python
# 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 BasisGlobal VariableLocal Variable
Definitiondeclared outside the functionsdeclared within the functions
LifetimeThey are created  the execution of the program begins and are lost when the program is endedThey are created when the function starts its execution and are lost when the function ends
Data SharingOffers Data SharingIt doesn’t offers Data Sharing
ScopeCan be access throughout the codeCan access only inside the function
Parameters neededparameter passing is not necessaryparameter passing is necessary
Storage A fixed location selected by the compilerThey are  kept on the stack
ValueOnce the value changes it is reflected throughout the codeonce changed the variable don’t affect other functions of the program

Global and Local Variables in Python – FAQs

What Is the Difference Between Global and Local Variables in Python?

Global Variables:

  • Scope: Accessible throughout the entire program or script, including all functions.
  • Declaration: Defined outside any function or class.
  • Lifetime: Exists for the duration of the program’s execution.
  • Example:
global_var = 10  # Global variable

def my_function():
print(global_var) # Accessing global variable

Local Variables:

  • Scope: Accessible only within the function or block where they are defined.
  • Declaration: Defined inside a function or block.
  • Lifetime: Exists only during the function’s execution.
  • Example:
def my_function():
local_var = 5 # Local variable
print(local_var) # Accessing local variable

my_function()
print(local_var) # Raises an error because local_var is not accessible here

How Can We Change a Global Variable from Inside a Function in Python?

To modify a global variable inside a function, use the global keyword. This tells Python that you are referring to the global variable, not creating a new local one.

Example:

global_var = 10

def change_global():
global global_var
global_var = 20 # Modify the global variable

change_global()
print(global_var) # Output: 20

What Is the Scope of a Local Variable in Python?

The scope of a local variable is limited to the function or block in which it is defined. It is not accessible outside that function or block.

Example:

def my_function():
local_var = 5 # Local variable
print(local_var) # Accessible here

my_function()
print(local_var) # Raises an error because local_var is not accessible outside the function

How Does Python Handle Variable Scopes in Nested Functions?

In nested functions, Python uses the LEGB rule (Local, Enclosing, Global, Built-in) to resolve variable scopes:

  • Local: Variables defined in the current function.
  • Enclosing: Variables in any enclosing functions (functions that are nested inside another function).
  • Global: Variables defined at the top level of the script or module.
  • Built-in: Python’s built-in names.

What Are the Best Practices for Using Global Variables in Python?

  1. Minimize Usage: Use global variables sparingly to avoid potential issues with code readability and maintainability.
  2. Encapsulation: Encapsulate global variables within classes or modules to limit their scope and manage their state more effectively.
  3. Avoid Side Effects: Be cautious when modifying global variables from different functions or modules to avoid unintended side effects.
  4. Use Constants: For immutable values, consider using constants and defining them in uppercase to signify their immutability.
  5. Document Changes: Clearly document where and why global variables are being modified, especially if changes occur in multiple places.
  6. Testing: Ensure thorough testing when using global variables to prevent unexpected behavior or bugs in different parts of the program.


Previous Article
Next Article

Similar Reads

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
How to Import Local Modules with Python
In Python, modules are self-contained files with reusable code units like functions, classes, and variables. Importing local modules allows for organizing the codebase effectively, enhance maintainability, and enhances code reuse. In this article, we will understand how to import local modules with Python. Understanding Modules and PackagesPython M
3 min read
Global Variable in Ruby
Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($). If we want to have a single variable, which is available across classes, we need to define a global variable. By default, an un
2 min read
PyQt5 QCalendarWidget - Mapping co-ordinate system from global
In this article we will see how we can map the co-ordinate system to the QCalendarWidget from the global. In order to do this we use mapFromGlobal method, this translates the global screen coordinate position to calendar coordinates.. In order to do this we will use mapFromGlobal method with the QCalendarWidget object.Syntax : calendar.mapFromGloba
2 min read
PyQt5 QCalendarWidget - Mapping co-ordinate system to global
In this article we will see how we can map the co-ordinate system from the QCalendarWidget to global. In order to do this we use mapToGlobal method, this translates the widget coordinate position to global screen coordinates. For example, mapToGlobal(QPoint(0, 0)) would give the global coordinates of the top-left pixel of the calendar. In order to
2 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
How to use Pickle to save and load Variables in Python?
Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text sp
2 min read
Mahotas - Bernsen local thresholding
In this article, we will see how we can implement bernsen local thresholding in mahotas. Bernsen's method is one of locally adaptive binarization methods developed for image segmentation. In this study, Bernsen's locally adaptive binarization method is implemented and then tested for different grayscale images. In this tutorial, we will use "luispe
2 min read
Mahotas - Local Minima in Image
In this article we will see how we can find local minima of the image in mahotas. Local minima is basically local peaks in the image. In this tutorial we will use “lena” image, below is the command to load it. mahotas.demos.load('lena') Below is the lena image In order to do this we will use mahotas.locmin methodSyntax : mahotas.locmin(img)Argument
2 min read
Mahotas - Local Maxima in Image
In this article we will see how we can find local maxima of the image in mahotas. Local maxima is basically local peaks in the image. In this tutorial we will use “lena” image, below is the command to load it. mahotas.demos.load('lena') Below is the lena image In order to do this we will use mahotas.locmax methodSyntax : mahotas.locmax(img)Argument
2 min read
How to load CSV data from the local to Snowflake?
In today's data-driven world, efficient data management and transfer are critical for business success. Snowflake, a powerful cloud-based data warehousing solution, allows organizations to store and analyze vast amounts of data seamlessly. In this article, we will cover everything from the basics to step-by-step instructions to load CSV to Snowflak
4 min read
How to Manage Local vs Production Settings in Django?
When developing a Django application, managing settings for different environments (local development, testing, staging, and production) is crucial for ensuring smooth deployment and security. You don't want the same settings (like debug mode or database credentials) for local development and production. In this article, we’ll explore different str
5 min read
Inserting variables to database table using Python
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. import sqlite3 To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you
3 min read
How are variables stored in Python - Stack or Heap?
Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection. Garbage Collection Garbage collection is a process in wh
3 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variable The location where we can find a variable and al
5 min read
Tracing Tkinter variables in Python
There is no inbuilt way to track variables in Python. But tkinter supports creating variable wrappers that can be used to do so by attaching an 'observer' callback to the variable. The tkinter.Variable class has constructors like BooleanVar, DoubleVar, IntVarand StringVar for boolean, double-precision floating-point values, integer and strings resp
3 min read
How to Create Dummy Variables in Python with Pandas?
A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. Explanation: As you can see three dummy
2 min read
Context Variables in Python
Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work with context variables in python. Note: This is supp
4 min read
Environment Variables in Python
In Python, its behavior is highly influenced by the setup of the environment variables. There is a fixed number of environment variables that Python recognizes and these generally are processed before the command line switches. Whenever a conflict arises between the environmental variable and the command line switches, the environment variable gets
4 min read
Assigning multiple variables in one line in Python
A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing values of data types. The assignment operator(=) assi
2 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read
How to check multiple variables against a value in Python?
Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example 1: C/C++ Code # assigning variables a = 100 b = 0
2 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
Article Tags :
Practice Tags :