Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Type Conversion in Python
Next article icon

Global and Local Variables in Python

Last Updated : 02 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, global variables are declared outside any function and can be accessed anywhere in the program, including inside functions. On the other hand, local variables are created within a function and are only accessible during that function’s execution. This means local variables exist only inside the function where they are defined and cannot be used outside it. Let’s understand each in detail.

Python Local Variables

Local variables are created within a function and exist only during its execution. They're not accessible from outside the function.

Example 1: In this example, we are creating and accessing a local variable inside a function.

Python
def greet():     msg = "Hello from inside the function!"     print(msg)  greet() 

Output
Hello from inside the function! 

Explanation: We define greet() with a local variable msg and print it. Since msg exists only during the function's execution, it's accessed within the function. Calling greet() displays the message.

Example 2: In this example, we are creating a local variable inside a function and then trying to access it outside the function, which causes an error.

Python
def greet():     msg = "Hello!"     print("Inside function:", msg)  greet() print("Outside function:", msg) 

Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 6, in <module>
print("Outside function:", msg)
^^^
NameError: name 'msg' is not defined

Explanation: msg is a local variable inside greet() and can only be accessed there. Printing it outside causes an error because it doesn't exist globally.

Python Global Variables

Global variables are defined outside all functions. They can be accessed and used in any part of the program, including inside functions.

Example 1: In this example, we are creating a global variable and then accessing it both inside and outside a function.

Python
msg = "Python is awesome!"  def display():     print("Inside function:", msg)  display() print("Outside function:", msg) 

Output
Inside function: Python is awesome! Outside function: Python is awesome! 

Explanation: msg is a global variable accessible both inside and outside the display() function. Calling display() prints the global msg and printing msg outside the function works as expected.

Example 2: In this example, we're creating a global variable and then using it both inside and outside a function.

Python
def fun():     print("Inside Function", s)  # Global scope s = "I love Geeksforgeeks" fun() print("Outside Function", s) 

Output
Inside Function I love Geeksforgeeks Outside Function I love Geeksforgeeks 

Explanation: s is a global variable accessed and printed inside fun(). Both calling fun() and printing s outside show the same global value.

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?

If a variable is defined both globally and locally with the same name, the local variable shadows the global variable inside the function. Changes to the local variable do not affect the global variable unless you explicitly declare the variable as global. Example:

Python
def fun():     s = "Me too."     print(s)  s = "I love Geeksforgeeks" fun()    print(s) 

Output
Me too. I love Geeksforgeeks 

Explanation: Inside fun(), s is a local variable set to "Me too." and prints that value. Outside, the global s remains "I love Geeksforgeeks", so printing s afterward shows the global value.

What if We Try to Modify a Global Variable Inside a Function?

Attempting to change a global variable inside a function without declaring it as global will cause an error. Example:

Python
def fun():     s += 'GFG'       print("Inside Function", s)  s = "I love Geeksforgeeks" fun() 

Output

UnboundLocalError: local variable 's' referenced before assignment

Explanation: fun() tries to modify s without declaring it global, so Python treats s as local but it’s used before assignment, causing an error. Declaring s as global inside fun() fixes this.

Modifying Global Variables Inside a Function

To modify a global variable inside a function, you must explicitly tell Python that you want to use the global version by using the global keyword. Example:

Python
def fun():     global s     s += ' GFG'   # Modify the global variable     print(s)     s = "Look for Geeksforgeeks Python Section"     print(s)  s = "Python is great!" fun() print(s) 

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

Explanation: Inside fun(), the global keyword lets Python modify the global variable s directly. The function first appends ' GFG' to "Python is great!", then reassigns s to "Look for Geeksforgeeks Python Section".

Example 2: This example demonstrates how Python handles global and local variables with the same name, and how the global keyword affects their behavior.

Python
a = 1  # Global variable  def f():     print('f():', a)  # Uses global a  def g():     a = 2  # Local variable shadows global     print('g():', a)  def h():     global a     a = 3  # Modifies global a     print('h():', a)  print('global:', a)   f()                   print('global:', a)  g()                  print('global:', a)   h()                   print('global:', a)   

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

Explanation:

  • f() prints the global a without changing it.
  • g() creates a local a that shadows the global one, leaving the global a unchanged.
  • h() uses global to modify the global a.
  • Only h() changes the global variable, f() and g() do not.

Difference b/w Local Variable Vs. Global Variables

Understanding local and global variables in Python is key, as they differ in scope and lifetime. Locals exist inside functions and global are accessible everywhere. This knowledge helps prevent bugs and write cleaner code. See the comparison table below for clarity.

Comparison 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

Next Article
Type Conversion in Python

K

kartik
Improve
Article Tags :
  • Misc
  • Python
Practice Tags :
  • Misc
  • python

Similar Reads

    How to Learn Python from Scratch in 2025
    Python is a general-purpose high-level programming language and is widely used among the developers’ community. Python was mainly developed with an emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.If you are new to programming and want to lea
    15+ min read
    Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPython’s simple and readable syntax makes it beginner-frien
    3 min read
    Python 3 basics
    Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
    10 min read
    Important differences between Python 2.x and Python 3.x with examples
    In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling
    5 min read
    Download and Install Python 3 Latest Version
    If you have started learning of Python programming, then for practice, Python installation is mandatory, and if you are looking for a guide that teaches you the whole process from downloading Python to installing it, then you are on the right path.Here in this download and install Python guide, we h
    6 min read
    Statement, Indentation and Comment in Python
    Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between 'Docstrings' and 'Multi-line Comments. What is Statement in Python A Pytho
    7 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 th
    3 min read
    Global and Local Variables in Python
    In Python, global variables are declared outside any function and can be accessed anywhere in the program, including inside functions. On the other hand, local variables are created within a function and are only accessible during that function’s execution. This means local variables exist only insi
    7 min read
    Type Conversion in Python
    Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Python Implicit Type C
    5 min read
    Private Variables in Python
    Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences