GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask
  • Introduction1 min read
  • Input & Output2 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Global and Local Variables in Python - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask

Global and Local Variables in Python

Last Updated : 21 Apr, 2026

Variables store data in memory and scope defines the specific region of a program where a variable is accessible. It dictates the visibility and lifetime of the variable within the source code. Variables are categorized into two primary scopes: Global and Local.

Local Variables

Local variables are defined inside a function and exist only during its execution. They cannot be accessed 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

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.

Global Variables

Global variables are declared outside all functions and can be accessed anywhere in the program, including inside functions.

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

Note: If a variable is not found inside a function (local scope), Python automatically looks for it in global scope. However, if a local variable has same name as a global one, it will shadow global variable inside that function.

Use of Local and Global variables

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

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.

Modifying Global Variables Inside a Function

By default, one cannot modify a global variable inside a function without declaring it as global. If you try, Python will raise an error because it treats variable as local. To modify a global variable use the global keyword.

Without global (causes error)

Python
def fun():
    s += ' GFG'   # Error: Python thinks s is local
    print(s)

s = "I love GeeksforGeeks"
fun()

Output

UnboundLocalError: local variable 's' referenced before assignment

Explanation: Inside fun(), Python assumes 's' is local since we try to modify it. But no local 's' exists before that line, so an error occurs.

With global (works correctly)

Python
s = "Python is great!"

def fun():
    global s
    s += " GFG"   # Modify global variable
    print(s)
    s = "Look for GeeksforGeeks Python Section"  # Reassign global
    print(s)

fun()
print(s)

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

Explanation:

  • Declaring 's' as global tells Python to use the variable from the global scope.
  • The function first appends " GFG", then reassigns 's'.
  • Changes persist outside the function.

Global vs Local with Same Name

Python
a = 1  # Global variable

def f():
    print("f():", a)  # Uses global a

def g():
    a = 2  # Local 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 global 'a' without changing it.
  • g() creates a local 'a', leaving global one untouched.
  • h() declares 'a' as global and modifies it.

Local Variable vs Global Variable

Comparison basisGlobal VariableLocal Variable
DefinitionDeclared outside functionsDeclared inside a function
LifetimeCreated when defined and exists until program ends or is deletedCreated when the function is called and destroyed when it returns
Data SharingShared across all functionsNot shared, exists only within its function
ScopeCan be accessed anywhere in the programAccessible only inside the function
Parameters neededNo parameter passing neededMay be created through parameters or assignments inside the function
StorageManaged in the global namespace (not fixed memory location)Stored in the function’s local namespace (stack frame)
ValueChanges affect the entire programChanges are local and don’t affect other functions
Comment

Explore

    Python Fundamentals
    • Introduction1 min read
    • Input & Output2 min read
    • Variables4 min read
    • Operators4 min read
    • Keywords2 min read
    • Data Types4 min read
    • Conditional Statements3 min read
    • Loops3 min read
    • Functions4 min read
    Python Data Structures
    • String4 min read
    • List3 min read
    • Tuples3 min read
    • Dictionary3 min read
    • Set2 min read
    • Arrays5 min read
    Advanced Python
    • OOP Concepts3 min read
    • Exception Handling5 min read
    • File Handling4 min read
    • Python Database2 min read
    • MongoDB3 min read
    • MySQL7 min read
    • Packages4 min read
    • Modules3 min read
    • DSA Libraries5 min read
    • Python GUI2 min read
    Data Science with Python
    • Numpy3 min read
    • Pandas4 min read
    • Matplotlib3 min read
    • Seaborn3 min read
    • StatsModel2 min read
    • Model Building6 min read
    • TensorFlow2 min read
    • PyTorch5 min read
    Web Development with Python
    • Flask3 min read
    • Django5 min read
    • Django ORM4 min read
    • Jinja2 Templating5 min read
    • Django Templates5 min read
    • REST API3 min read
    • Build API with DRF4 min read
    Python Practice
    • Quiz1 min read
    • Practice Problems2 min read
    • Interview Q & A15+ min read
    Courses
    • Placement 360 Course2 min read
    • Data Science 360 Course2 min read
    • AI Engg Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.