top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Global Variable in Python

Introduction

Variable scope is a basic idea in Python and programming in general. Writing maintainable and error-free code requires an understanding of how variables operate in various scopes. One of the two scopes of variables is the global variable in Python. This tutorial aims to provide a clear and informative insight into the topic of global variables in Python.

Overview

Global variables in Python are a fundamental concept in programming. This tutorial aims to offer an organized insight into the vast topic of global variables and how to use the concept in your programming journey.

What Are Global Variables in Python?

Global variables in Python are variables that you define at the script or modules level, outside of any specific function. They have a scope meaning they can be accessed from, within the codebase or module. This allows them to be utilized throughout the program rather than being restricted to a single function or block of code.

An example of creating and utilizing a global variable in Python is shown below:

Code:

# Define a global variable
my_global_variable = 100

def my_function():
    # Access the global variable
    print(my_global_variable)

# Call the function
my_function()  # Output: 100

# You can also modify the global variable within a function
def modify_global_variable():
    global my_global_variable
    my_global_variable = 205

modify_global_variable()

# Now the global variable has been modified
print(my_global_variable)  # Output: 205

The use of the global keyword holds significance when making changes to a global variable within a function. It guarantee­s that you are manipulating the intended global variable and not a newly created local variable with the same name.

The example above demonstrates how my_global_variable re­mains modifiable both inside and outside functions since it is defined at the top level of the script.

It's crucial to use global variables sparingly because doing so can make your code less modular and more challenging to comprehend and debug. Instead of extensively depending on global variables, it is frequently advised to encapsulate data within functions or classes and pass values between them as arguments or attributes.

Creating Local Variables in Python

Local variables in Python are those that are declared inside a particular function or block of code and are only usable inside that function or block. Local variables are only used within the function or block in which they are defined and have a constrained scope.

In Python, local variables are created by merely giving a variable name and value within a function or a block of code. Here's an example:

Code:

def our_function():
    # Define the local variable
    our_local_variable = 50
    print(our_local_variable)

# Call the function
our_function()  # Output: 50

# Trying to access the our_local_variable outside the function will result in an error
# print(our_local_variable)  # This will raise a NameError

In the above case, our_local_variable is a local variable because it is defined inside the our_function function. It can only be accessed and used in the context of that function. You will see a NameError if you attempt to access our_local_variable from outside of our_function because it is not defined there.

To store and alter data within a single function without affecting other areas of the program, local variables are often utilized. They are separate from the global scope and do not conflict with variables defined in other functions or the global variables.

What is Variable Scope in Python?

In Python, the term "variable scope" describes the area or context in which a variable is declared and accessible. It specifies the guidelines for how variables should be displayed and usable in various Python code sections.

The two primary types of variable scope in Python are:

Local scope

Variables defined inside a particular function or block of code are known as local scope. These variables are not visible or useful outside of that function or block; only that function or block has access to them. The local variables are normally erased when the function or block ends, so their values are no longer accessible. Let us look at an example:

Code:

def our_function():
    our_local_variable = 50
    print(our_local_variable)

our_function()  # This works
# print(local_variable)  # This will raise a NameError because local_variable is not defined here

Global scope

Variables defined outside of any functions or blocks at the top level of a script or module are known as global scope. The script or module's global variables can be accessible from anywhere, including inside functions. To be sure you're referring to the global variable and not defining a new local variable with the same name when you want to edit a global variable inside of a function, you must use the global keyword. Let us look at an example:

Code:

our_global_variable = 109
def our_function():
    print(our_global_variable)
our_function()  # This works because global_variable is accessible inside the function

Creating Global Variables in Python

By defining them at the top level of a script or module in Python, separate from any functions or blocks, you can create global variables. Global variables are available from anywhere in the script or module, including inside functions, because they have a global scope. You may make and use global variables in the following way:

Code:

# Define global variables
my_global_variable_1 = 100
my_global_variable_2 = "Hello, World!"

def my_function():
    # Access global variables
    print(my_global_variable_1)
    print(my_global_variable_2)

# Call the function
my_function()  # Output: 100, Hello, World!

# Modify a global variable from within a function
def modify_global_variable():
    global my_global_variable_1
    my_global_variable_1 = 20

modify_global_variable()

# Now the my_global_variable_1 has been modified
print(my_global_variable_1)  # Output: 20

The global_variable_1 and global_variable_2 are defined at the top level of the script in the aforementioned example, making them variables. Both inside and outside of the my_function function, you can access these variables. Use the global keyword before the variable name, as seen in the modify_global_variable function, to change a global variable from within a function.

Accessing Global Variables Inside and Outside Functions

As long as you define global variables at the top level of your script or module, you can access them both inside and outside of a function in Python. For accessing a global variable both inside and outside of a function, follow these steps:

Accessing a global variable inside a function

You don't need to use any additional keywords or declarations to access a global variable inside of a function; just use the variable name.

Code:

global_variable_1 = 100
def my_function_1():
    # Access the global variable
    print(global_variable_1)

my_function_1()  # Output: 100

The global_variable_1 can be accessed in the my_function_1 function because it is defined globally.

Accessing a global variable outside a function

You can also use the variable name directly, as you would for any other variable, to access a global variable outside of a function.

Code:

global_variable_2 = 30

def my_function_2():
    pass  # This function does not use global_variable

# Access the global variable outside of the function
print(global_variable_2)  # Output: 300

Since global_variable_2 has a global scope, even though we access it outside of the my_function_2 function, it is still available.

It's crucial to remember that global variables can have their values changed from within a function by using the global keyword. For instance:

Code:

global_variable_3 = 30

def modify_global_variable():
    global global_variable_3
    global_variable_3 = 50

modify_global_variable()

print(global_variable_3)  # Output: 50

The global keyword is used in this instance by the modify_global_variable function to signal that it wishes to change the global variable global_variable_3. 50 is assigned to the global variable after the function has been called.

Creating Variables With Local Scope in Python

By declaring variables within a particular function or block of code, you can construct variables with local scope in Python. Local variables cannot be seen outside of the function or block in which they are defined and are only useful within that area. Here are some illustrations of local scope variables:

Local variables inside a function

Code:

def my_function_1():
    # Define local variables
    local_var_1 = 101
    local_var_2 = "Hello, World!"
    
    # Access and use local variables
    print(local_var_1)
    print(local_var_2)

my_function_1()  # Output: 101, Hello, World!

# Trying to access local variables outside the function will result in an error
# print(local_var_1)  # This will raise a NameError
# print(local_var_2)  # This will raise a NameError

In this case, the local variables local_var_1 and local_var_2 are defined inside the my_function function. They are only accessible and usable within the boundaries of my_function_1.

Local variables inside a block

Code:

def check_age(age_1):
    if age_1 >= 18:
        # Define a local variable inside the block
        can_vote_1 = True
    else:
        # Define another local variable inside the block
        can_vote_1 = False
    
    # Access and use local variables
    print("Can vote:", can_vote_1)

check_age(21)  # Output: Can vote: True
check_age(16)  # Output: Can vote: False

# Trying to access can_vote outside the block will result in an error
# print(can_vote_1)  # This will raise a NameError

The can_vote_1 is defined in conditional blocks in this example. It can only be accessed within those blocks because it is a local variable with block-level scope.

To store and modify data within a single function or block without affecting other areas of your code, local variables are useful. They are transitory and ideal for handling temporary data because they are separated from the global scope and normally removed when the function or block ends.

Why Are Global and Local Variables Used in Python?

In Python, local and global variables have distinct functions that are utilized to accomplish diverse programmatic objectives. For the following reasons, Python uses local and global variables:

Local variables

  • Data that is unique to a given function or section of code is stored in local variables. This separation guarantees that the data won't affect other program components.

  • Local variables are transient and only exist while the function or block of code in which they are defined is active. They are useful for storing temporary data and interim findings while a particular task is being carried out.

Global variables

  • Data that needs to be shared and accessible by various areas of a program is stored in global variables. They make it possible for several functions or blocks to utilize the same data.

  • Constants that are utilized throughout the program or configuration settings can be stored in global variables. The management of these variables is centralized as a result.

Differences Between Global Variable and Local Variable

Aspect

Local variables

Global variables

Scope

Restricted to the particular function or block in which they are defined.



Accessible through functions as well as from elsewhere in the program.



Lifetime

Exist solely throughout the course of the function or block where they are defined.



Exist for the duration of the program's execution.

Accessibility

Outside of the function or block where they are defined, they are not visible or accessible.

Available from every section of the program.



Purpose

Used to keep transitory information and draught outcomes in a particular context.



Used to store data that must be shared and accessed by other program components.



Data isolation

Avoid naming conflicts between functions, and guarantee data isolation.



If not used appropriately, global variables can result in name disputes.


Conclusion

In summary, global variables in Python provide a mechanism to share and access data throughout various program components. They can be used from anywhere in the program, including within functions, because they have a global scope.

FAQs

1. What occurs if you attempt to access a global variable in Python that is not defined?

Because Python cannot identify the variable, accessing an undefined global variable will result in a NameError.

2. Is it feasible to use numerous functions to alter the value of a global variable?

As long as the global keyword is used in each function that alters the global variables in Python, you can change the value of a global variable from numerous functions.

3. Can Python programs encounter potential problems as a result of global variables?

Yes, using too many global variables can reduce modularity and make code more difficult to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *