Banner Image

Python

Global and Local Variables in Python

Written by Rahul Lath

Updated on: 07 Dec 2023

Python Tutorials

1Python Overview2Python Tutorial: A Comprehensive Guide for Beginners3Python Keywords and Identifiers4Download and Installation Guide for Python5Python Syntax (With Examples)6Python Comments7Python Variables (With Examples)8Taking Input in Python9Output in Python10File Handling in Python (Files I/O)11Python Operators (With Examples)12Ternary Operators in Python13Operator Overloading in Python14Division Operators in Python15Input from Console in Python16Output Formatting in Python17Any All in Python18Difference between Python Equality and Identity Operators19Python Membership and Identity Operators20Python Data Types21Python Dictionary22Control Flow in Python23Python Arrays24Looping Techniques in Python25Chaining Comparison Operators in Python26Python Functions27Python Strings28Python Numbers29Python Sets30Python For Loops31Python While Loops32Python Break Statement:33Python Continue Statement34Python pass Statement35Args and Kwargs in Python36Python Generators37Python Lambda38Global and Local Variables in Python39Global Keyword in Python40Python Closures41Python Decorators42Memoization using Decorators in Python43Constructors in Python44Encapsulation in Python45Inheritance in Python46Polymorphism in Python47Class Method vs Static Method in Python48Python Exception Handling49First Class Functions in Python50Python Classes And Objects51Errors and Exceptions in Python52Built-In Exceptions in Python53Append to file in Python54File Handling in Python55Destructors in Python56User-Defined Exceptions in Python57Class or Static Variable in Python58Python Tuples59Reading File in Python60Writing File in Python61Opening and Closing Files in Python62NZEC error in Python63Operator Function64Webscraper Python Beautifulsoup65Python Pyramid Patterns66Python Start Patterns67Web Crawler in Python68Build a Python Youtube Downloader69Currency Convertor in Python70Python Website Blocker
tutor Pic

Global and local variables in python are the two types of variables in python.

A variable that is declared inside a function or a block of code and can only be accessed inside that function or block is known as a local variable. In contrast, a global variable is one that is defined outside of a function or block and is accessible throughout the entire program.

Data values are stored in variables in Python so they can be accessed and changed at any time. In essence, a variable is a named storage location with a value in the computer’s memory.

The scope of local and global variables is the primary distinction. In contrast to global variables, which can be accessed from anywhere in the program, local variables are only accessible within the function or block in which they are defined. This indicates that whereas global variables have a wider scope, local variables have a more constrained one.

When temporary data needs to be stored within a function or block of code, local variables are used. They are helpful for storing information that will only be needed temporarily and won’t need to be accessed outside of the function or block. On the other hand, global variables are helpful for storing information that must be accessed and changed throughout the program.

Declaring and Assigning Local Variables

Local variables are those that are declared and assigned inside of a function or code block. A local variable’s range is constrained to the function or block in which it is defined. In Python, you simply give a variable name a value inside a function or block to declare a local variable. 

For example, let’s say we want to create a function that calculates the area of a rectangle. We can declare and assign local variables for the length and width of the rectangle within the function as follows:

In this example, the variables length and width are declared and assigned within the calculate_area() function. These variables are local to the function and cannot be accessed outside of it. The variable area is also a local variable, but it is calculated based on the values of length and width.

To use the calculate_area() function, we simply call it as follows:

In conclusion, local and global variables are important concepts in Python programming. Local variables are used to store temporary data within a function or block of code, while global variables are used to store data that needs to be accessed and manipulated throughout the program. Understanding the difference between these two types of variables is crucial for writing efficient and effective Python programs.

Declaring and Assigning Global Variables

Global variables can be accessed from anywhere in the program and are defined outside of a function or block of code. A global variable can be accessed from anywhere in the program, including within functions or blocks of code, because its scope is wider than that of a local variable.

To declare and assign a global variable in Python, you use the global keyword followed by the variable name. This tells Python that you want to create a global variable rather than a local variable.

For example, let’s say we want to create a global variable called name that we can access from anywhere in the program. We can do this as follows:

In this example, the global keyword is used to declare the variable name as a global variable within the print_name() function. The variable name is then assigned the value “John” within the function. After calling the function, we can also access the global variable name outside the function and print its value.

Differences Between Local and Global Variables

The scope of local and global variables is the primary distinction. In contrast to global variables, which can be accessed from anywhere in the program, local variables are only accessible within the function or block in which they are defined. Another distinction is that although local and global variables may share the same name, they are distinct variables with different values.

For example, let’s say we have a global variable called x and we also define a local variable called x within a function. The local variable x will be a different variable with a different value than the global variable x.

In this example, the global variable x is assigned the value 10. Within the my_function() function, we define a local variable also called x and assign it the value 5. When we call the function, it will output the value of the local variable x, which is 5. However, outside the function, the value of the global variable x is still 10.

Modifying Local and Global Variables

In Python, variables can have their values changed at the local and global levels. When a local variable is changed, only the function or block of code where the variable is defined is affected by the new value. When a global variable is changed, all of the program’s instances where it is used are affected by the new value.

For example, let’s say we have a global variable called count that we want to increment within a function. We can do this as follows:

In this example, the increment_count() function uses the global keyword to access the global variable count. Within the function, the value of count is incremented by 1. After calling the function, we print the value of count and it will output 1.

Best Practices for Using Local and Global Variables

To write clear and effective code when using local and global variables in Python, it’s important to adhere to some best practices.

One suggestion is to use global variables as little as possible. Because changes to global variables can alter the behavior of the entire program, global variables can make code challenging to comprehend and debug. Instead, use local variables within functions or blocks of code as much as possible, as they have a smaller scope and are easier to manage.

Another suggestion is to give variables meaningful names. When working on complex programs with lots of variables, this makes the code more readable and understandable. Avoid using the same variable name for local and global variables as this can cause misunderstandings and mistakes.

When using local and global variables, common mistakes to avoid include accidentally redefining a global variable inside of a function or block of code, using global variables excessively, and failing to initialize variables correctly before using them.

Here is an illustration of how to use local and global variables in Python effectively:

/Code start/  # Properly initialize variables before using them total = 0 for i in range(1, 11): total += i print("The total is:", total) 

Written by

Rahul Lath

Reviewed by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic