How to Set Global Variables in Python Functions?

In this tutorial, I will explain how to set global variables in Python functions. Someone asked me about setting global variables in Python functions in the Python training classes, which made me explore more about this topic and find four important methods to achieve this task, I will share my findings with suitable examples and screenshots.

Set Global Variables in Python Functions

Let us explore different ways to set global variables in Python with an example to make it more relatable.

Read How to Use the arange() Function in Python?

1. Use the global Keyword

To modify a global variable inside a function in Python, you must declare it as global first.

Example: Set the National Minimum Wage in the USA

# Global variable representing the minimum wage in the USA
minimum_wage = 7.25  # As of federal law in 2024

def update_minimum_wage(new_wage):
    global minimum_wage  # Declare that we're modifying the global variable
    minimum_wage = new_wage  # Update the global variable
    print(f"Updated federal minimum wage: ${minimum_wage}")

update_minimum_wage(15.00)  # Setting new minimum wage
print(f"Current federal minimum wage: ${minimum_wage}")

Output:

Updated federal minimum wage: $15.0
Current federal minimum wage: $15.0

You can refer to the screenshot below to see the output.

Set Global Variables in Python Functions

Without global, Python would create a new local variable inside the function instead of modifying the global one.

Check out How to Use the insert() Function in Python?

2. Use the Global Dictionary

A better approach is using a Python dictionary to store values that need to be changed globally.

Example: Update State-Specific Tax Rates

# Dictionary to store state-wise tax rates
state_tax_rates = {
    "California": 7.25,
    "Texas": 6.25,
    "New York": 4.00
}

def update_tax_rate(state, new_rate):
    global state_tax_rates  # Declare that we're modifying the global dictionary
    if state in state_tax_rates:
        state_tax_rates[state] = new_rate
        print(f"Updated tax rate for {state}: {new_rate}%")
    else:
        print(f"{state} is not in the tax records.")

update_tax_rate("California", 8.00)
print(state_tax_rates) 

Output:

Updated tax rate for California: 8.0%
{'California': 8.0, 'Texas': 6.25, 'New York': 4.0}

You can refer to the screenshot below to see the output.

How to Set Global Variables in Python Functions

Using a dictionary allows managing multiple states efficiently instead of using multiple separate global variables.

Read How to Use the strip() Function in Python?

3. Use the globals() Method

Python provides the globals() function, which allows accessing and modifying global variables dynamically.

Example: Update Federal Holidays in the USA

# Global list of federal holidays
federal_holidays = ["New Year's Day", "Independence Day", "Christmas Day"]

def add_holiday(new_holiday):
    globals()['federal_holidays'].append(new_holiday)  # Modify global list
    print(f"Added holiday: {new_holiday}")

add_holiday("Thanksgiving Day")  
print(federal_holidays) 

Output:

Added holiday: Thanksgiving Day
["New Year's Day", 'Independence Day', 'Christmas Day', 'Thanksgiving Day']

You can refer to the screenshot below to see the output.

Set Global Variables in Python Functions globals()

This approach is useful when dynamically modifying a global variable inside a function.

Check out How to Use the trim() Function in Python?

4. Use a Class

Instead of using Python’s global , a cleaner approach is to store global values inside a class.

Example: Manage National Park Entry Fees in the USA.

class NationalPark:
    entry_fee = 25  # Default entry fee in USD

    @classmethod
    def update_fee(cls, new_fee):
        cls.entry_fee = new_fee
        print(f"Updated national park entry fee: ${cls.entry_fee}")

# Updating the entry fee
NationalPark.update_fee(30)
print(NationalPark.entry_fee)

Output:

30

Using a class helps keep global variables structured and avoids unnecessary global variables.

Read How to Use the Floor() Function in Python?

Conclusion

In this tutorial, I explained how to set global variables in Python functions. I discussed four methods to accomplish this task, they are using global keyword, global dictionary, globals() method, and using a class.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.