A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/global-local-variables-python/ below:

Global and Local Variables in Python

Global and Local Variables in Python

Last Updated : 02 Jun, 2025

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:

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4