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()
OutputHello 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)
OutputInside 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)
OutputInside 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)
OutputMe 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)
OutputPython 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)
Outputglobal: 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 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 |
---|
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