Back to Blog
Python

Python Global Variables: A Friendly Guide with Practical Examples

9/9/2025
5 min read
Python Global Variables: A Friendly Guide with Practical Examples

Confused by global variables in Python? Learn what they are, how to use the global keyword, and why you should use them sparingly in this easy-to-follow guide.

Python Global Variables: A Friendly Guide with Practical Examples

Python Global Variables: A Friendly Guide with Practical Examples

Python Global Variables: Taming the Beasts of Scope

Hey there, fellow coder! 👋

If you've been journeying through Python, you've undoubtedly run into a situation like this: you define a variable, try to use it inside a function, and then... BAM! You're greeted with an UnboundLocalError. It’s frustrating, right? You know the variable is right there, but Python acts like it can't see it.

This usually leads you down the path to discovering global variables. They seem like the perfect solution at first, but then you might hear seasoned developers whisper, "Global variables are bad practice!" So, what's the deal?

Let's break it down together, in plain English. We'll talk about what they are, how to use them, and why they have such a bad reputation.

What Exactly is a Global Variable?

Imagine your code is a big office building.

  • Local variables are like private conversations inside a specific meeting room. No one outside the room can hear them.

  • Global variables are like announcements made over the building's intercom. Everyone, in every room, can hear them.

In technical terms, a global variable is one that is defined in the main body of a script, outside of any functions. It's accessible from anywhere in your code—both inside and outside functions.

python

# This is a GLOBAL variable. It's declared in the main script.
company_name = "CoderCrafter Inc."

def welcome_employee():
    # This function can ACCESS the global variable
    print(f"Welcome to {company_name}!")

welcome_employee()  # Output: Welcome to CoderCrafter Inc!
print(company_name) # Output: CoderCrafter Inc.

See? The company_name is available everywhere.

The Problem: The "Bossy" Function

Now, let's try to change that global variable from inside a function.

python

company_name = "CoderCrafter Inc."

def change_company():
    company_name = "DataDriven Devs" # Trying to change it
    print(f"Inside function: {company_name}")

change_company()  # Output: Inside function: DataDriven Devs
print(f"Outside function: {company_name}") # Output: Outside function: CoderCrafter Inc.

Wait, what? The change didn't stick outside the function!

This is the core of the confusion. When you write variable = value inside a function, Python assumes you want to create a brand new local variable that just happens to have the same name. It doesn't touch the global one.

The Solution: The global Keyword

To tell Python, "Hey, I don't want a new local variable; I want to use and modify the global one," you need to use the global keyword. It's like raising your hand and declaring your intentions.

python

company_name = "CoderCrafter Inc."

def change_company():
    global company_name  # This is the magic line!
    company_name = "DataDriven Devs"
    print(f"Inside function: {company_name}")

change_company()  # Output: Inside function: DataDriven Devs
print(f"Outside function: {company_name}") # Output: Outside function: DataDriven Devs

Now it works! By using global company_name, we told the function to use the variable from the global scope.

Why the Bad Reputation? A Word of Caution.

Using global seems easy, so why do many developers advise against it? Think back to our office building analogy.

If everyone is constantly using the intercom (global variables), things get chaotic very quickly.

  1. Spaghetti Code: It becomes hard to track where a variable is changed. A function halfway across your script could be modifying a value, making bugs incredibly difficult to find and debug ("Who changed this?!").

  2. Unpredictable Code: Functions that rely on global variables are not self-contained. Their behavior doesn't just depend on their inputs; it depends on the state of the entire program, which makes them unreliable.

  3. Testing Nightmare: To test a function that uses globals, you have to set up the exact global state first. This is messy and error-prone compared to testing a function that only uses what you pass into it.

What Should You Do Instead?

The goal is to write predictable, easy-to-debug functions. Here are two better alternatives:

1. Pass Arguments and Return Values: This is the cleanest and most preferred way. Make your functions rely only on their parameters and explicitly return results.

python

# A better, self-contained function
def create_welcome_message(company):
    return f"Welcome to {company}!"

company_name = "CoderCrafter Inc."
message = create_welcome_message(company_name)
print(message)

2. Use Classes and Attributes: If you need to share state across multiple functions, a class is often a perfect solution. The data is neatly bundled together.

python

class Company:
    def __init__(self, name):
        self.name = name # 'self.name' is like an attribute shared by all class methods

    def welcome(self):
        print(f"Welcome to {self.name}!")

    def rename(self, new_name):
        self.name = new_name

# Using the class
my_company = Company("CoderCrafter Inc.")
my_company.welcome() # Output: Welcome to CoderCrafter Inc!

my_company.rename("DataDriven Devs")
my_company.welcome() # Output: Welcome to DataDriven Devs!

The Bottom Line

Global variables and the global keyword are tools in your Python toolbox. It's important to understand how they work, but it's even more important to know when to use them.

  • Use global sparingly, for things that truly need to be application-wide constants (like PI, CONFIG_SETTINGS loaded at startup).

  • For almost everything else, favor passing arguments and using return values or classes. Your future self (and anyone else who reads your code) will thank you for the clarity.

  • Found this helpful? Explore more beginner-friendly Python tutorials on https://codercrafter.in!

Flex Your Coding Muscles: 5 Python Variable Exercises for Beginners

So, you've been learning about Python variables. You know about strings, integers, and maybe even how to use the global keyword. You've read the theory, but now you're thinking, "Okay, but can I actually use this stuff?"

Absolutely! The best way to learn is by doing. Reading is like watching someone else work out—you only get stronger when you lift the weights yourself.

That's why we've put together these 5 practical exercises focused on Python variables. Don't just skim through them! Open your code editor (VS Code, PyCharm, or even a simple REPL), try to solve them yourself, and then check the solutions.

Let's get those mental reps in. 💪


Exercise 1: The Switcheroo

The Task: You have two variables, a and b. Your goal is to swap their values.
a should end up with b's initial value, and b should get a's initial value.

Your Code Starts Here:

python

a = 10
b = 20

# Write your swapping code here.

print(a) # Should print 20
print(b) # Should print 10

<details> <summary><strong>Hint (Try yourself first!)</strong></summary> You'll need a temporary variable to hold one of the values. </details>
<details> <summary><strong>Check Your Solution</strong></summary>

python

a = 10
b = 20

# Use a temporary variable 'temp'
temp = a   # Save the value of 'a'
a = b      # Now assign 'b' to 'a'
b = temp   # Finally, assign the saved value to 'b'

print(a) # 20
print(b) # 10

Bonus: In Python, you can swap without a temp variable in one line: a, b = b, a. How cool is that?

</details>


Exercise 2: The Personalizer

The Task: Ask the user for their name and their favorite color using the input() function. Then, print a personalized message that combines both pieces of information in a sentence.

Your Code Starts Here:

python

# Your code here. Use input().
# Example output: "Hi Anna! Your favorite color, blue, is really cool!"

<details> <summary><strong>Check Your Solution</strong></summary>

python

name = input("What is your name? ")
color = input("What is your favorite color? ")

# Use string concatenation
message = "Hi " + name + "! Your favorite color, " + color + ", is really cool!"
print(message)

# Or use f-strings (a more modern way!)
message = f"Hi {name}! Your favorite color, {color}, is really cool!"
print(message)

</details>


Exercise 3: The Global Check

The Task: This one builds on our previous post about Global Variables in Python. The code below has an error. Fix it using the global keyword so it correctly modifies the global variable counter.

python

counter = 0

def increment():
    # Fix the problem on this line
    counter += 1
    print(f"Counter is now: {counter}")

increment()
increment()
print(f"Final counter: {counter}") # This should print 2

<details> <summary><strong>Check Your Solution</strong></summary>

python

counter = 0

def increment():
    global counter  # This tells Python to use the global 'counter'
    counter += 1
    print(f"Counter is now: {counter}")

increment() # Counter is now: 1
increment() # Counter is now: 2
print(f"Final counter: {counter}") # Final counter: 2

Remember, you need to declare global counter inside the function to modify the global variable.

</details>


Exercise 4: The Type Investigator

The Task: Create variables with different data types (e.g., integer, string, float, boolean). Write a program that prints both the value and the type of each variable. Use the type() function.

Your Code Starts Here:

python

# Create your variables here.

# Print their value and type here.
# Example output: "Value: 10, Type: <class 'int'>"

<details> <summary><strong>Check Your Solution</strong></summary>

python

my_int = 10
my_float = 20.5
my_string = "Hello"
my_bool = True

print(f"Value: {my_int}, Type: {type(my_int)}")
print(f"Value: {my_float}, Type: {type(my_float)}")
print(f"Value: {my_string}, Type: {type(my_string)}")
print(f"Value: {my_bool}, Type: {type(my_bool)}")

Understanding types is crucial for debugging later on!

</details>


Exercise 5: The Simple Calculator

The Task: Create a simple calculator that takes two numbers from the user and prints the sum, difference, product, and quotient.

Your Code Starts Here:

python

# Get two numbers from the user
# Remember: input() returns a string, so you need to convert to int/float.

# Calculate and print all four operations.

<details> <summary><strong>Check Your Solution</strong></summary>

python

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2

print(f"Sum: {sum}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")

Note: We use float() instead of int() to allow for decimal numbers. What happens if you try to divide by zero? 🤔 (That's an error you'll learn to handle later!)

Found this helpful? Explore more beginner-friendly Python tutorials on https://codercrafter.in!

</details>


Related Articles