Global and Local Variables in Python
Last Updated :
25 Jul, 2024
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()
OutputI 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)
OutputInside 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)
OutputMe 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)
OutputPython 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)
Outputglobal : 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 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 |
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?
- Minimize Usage: Use global variables sparingly to avoid potential issues with code readability and maintainability.
- Encapsulation: Encapsulate global variables within classes or modules to limit their scope and manage their state more effectively.
- Avoid Side Effects: Be cautious when modifying global variables from different functions or modules to avoid unintended side effects.
- Use Constants: For immutable values, consider using constants and defining them in uppercase to signify their immutability.
- Document Changes: Clearly document where and why global variables are being modified, especially if changes occur in multiple places.
- Testing: Ensure thorough testing when using global variables to prevent unexpected behavior or bugs in different parts of the program.
Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today
Similar Reads
How to Learn Python from Scratch in 2024
Python is a general-purpose high-level programming language and is widely used among the developersâ community. Python was mainly developed for 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 learn
15+ min read
Python Introduction
Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines o
5 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
To understand how to Download Python and Install Python You need to know What Python is and where it is actually installed in your system. Let's consider a few points: Python is a widely used general-purpose, high-level programming language. Every Release of Python is open-source. Python releases ha
4 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
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 insid
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
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Taking input in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ()
3 min read
Taking multiple inputs from user in Python
While taking a single input from a user is straightforward using the input() function, many real world scenarios require the user to provide multiple pieces of data at once. This article will explore various ways to take multiple inputs from the user in Python. Using input() and split()One of the si
5 min read
Python - Print Output using print() function
Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it's various operations. [GFGTABS] Python # print() function example print("GeeksforGeeks") a = [1, 2, 'gfg'] pri
4 min read
Python end parameter in print()
By default Python's print() function ends with a newline. A programmer with C/C++ background may wonder how to print without a newline. Python's print() function comes with a parameter called 'end'. By default, the value of this parameter is '\n', i.e. the new line character. [GFGTABS] Python # ends
2 min read
Python - Output Formatting
In Python, output formatting refers to the way data is presented when printed or logged. Proper formatting makes information more understandable and actionable. Python provides several ways to format strings effectively, ranging from old-style formatting to the newer f-string approach. Formatting Ou
6 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Ternary Operator in Python
The ternary operator in Python allows us to perform conditional checks and assign values or perform operations on a single line. It is also known as a conditional expression because it evaluates a condition and returns one value if the condition is True and another if it is False. Basic Example of T
5 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python | a += b is not always a = a + b
In Python, a += b doesn't always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables. before that, we will try to understand the difference b
4 min read
Difference between == and is operator in Python
In Python, == and is operators are both used for comparison but they serve different purposes. The == operator checks for equality of values which means it evaluates whether the values of two objects are the same. On the other hand, is operator checks for identity, meaning it determines whether two
4 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
3 min read
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
5 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
5 min read
Python Tuples
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
7 min read