You should use the global keyword when you need to modify a global variable inside a function. Without it, Python will assume you’re working with a local variable, and the changes won’t affect the global scope.
How to use Python global keyword
Short answer:
In Python, a global variable is a variable declared outside any function, meaning it exists in the global scope. This makes it accessible from anywhere in our code, both inside and outside functions. However, while we can access a global variable inside a function, we can't modify it from within a function unless we explicitly use the global keyword with the global variable.
This lets us change the global variable inside our current function. It tells Python that when we use or update that variable, we're referring to the one defined globally, not the one inside the function.
When should we use Python global keyword?
In Python, variables created inside a function are local to that function and cannot be directly accessed outside of it. However, there are times when you might want to modify a variable that exists outside the function's scope (i.e., a global variable). This is where the global keyword becomes useful.
When we declare a variable with the global keyword inside a function, we're telling Python that we want to use the globally defined variable instead of creating a new local one. Once declared, we can modify the variable, and these changes persist outside the function.
Example of using the global keyword
Imagine we are working on an application where a global counter tracks the number of tasks completed. We might want to update this counter from various parts of your program, including within functions.
Without the global keyword, the following code will throw an error because we're trying to modify a variable outside the function’s scope:
completed_tasks = 0def complete_task():completed_tasks += 1 # Error! Python treats this as a local variableprint(f"Tasks completed: {completed_tasks}")# Call the function multiple timescomplete_task()complete_task()complete_task()
Python has raised an UnboundLocalError because it's trying to modify the completed_tasks variable without knowing it's defined globally.
Let's see what happens when we try to modify the same global variable within a function after declaring it as global. The example below demonstrates the use of global:
# Global variable to track the number of completed taskscompleted_tasks = 0def complete_task():global completed_tasks # Declare that we are using the global variablecompleted_tasks += 1 # Modify the global variable inside the functionprint(f"Tasks completed: {completed_tasks}")# Call the function multiple timescomplete_task()complete_task()complete_task()
In this example, the global keyword allows the complete_task function to modify the completed_tasks global variable, keeping track of the completed tasks across function calls.
Note: A variable cannot be declared
globaland assigned a value in the same line.
Using the global keyword in different scenarios
Let’s expand our task management example.
global keyword in for loops
Imagine you want to process tasks in a list and update the global counter as you complete them:
tasks = ["Task 1", "Task 2", "Task 3"]# Global variable to track the number of completed taskscompleted_tasks = 0# Function to process tasks and update the global completed_tasks variabledef process_tasks():global completed_tasks # Declare that we are modifying the global variable completed_tasksfor task in tasks: # Iterate through each task in the tasks listprint(f"Processing: {task}") # Print the current task being processedcompleted_tasks += 1 # Increment the completed_tasks count by 1 for each task processedprint(f"Total tasks completed: {completed_tasks}") # Print the total number of completed tasks# Call the function to process the tasksprocess_tasks()
In this case, the global keyword ensures that the completed_tasks variable is updated as tasks are processed.
global keyword in nested loops
What if you had tasks for different departments, and you wanted to process them using nested loops? Here’s how the global keyword works:
# Global variable to track the number of completed taskscompleted_tasks = 0# Function to process batches of tasks and count "done" tasksdef nested_task_manager(task_batches):global completed_tasks # Declare that we are modifying the global variable completed_tasksfor batch in task_batches: # Iterate through each batch in the task_batches listfor task in batch: # Iterate through each task within a batchif task == "done": # If the task is marked as "done"completed_tasks += 1 # Increment the completed_tasks count by 1 for each "done" taskprint(f"All batches processed. Completed tasks: {completed_tasks}")# List of task batches, each containing a series of tasks marked as "done" or "pending"task_batches = [["done", "done"], ["pending", "done"], ["done", "pending"]]# Call the function to process the task batchesnested_task_manager(task_batches) # Output: All batches processed. Completed tasks: 4
Again, the global keyword allows us to update the global completed_tasks variable while processing tasks from different departments.
Let us see a comprehensive example to sum up the functionality of the global keyword:
Before running the code, predict the output of each
ybe at each stage?
y = 1def foo():print ("Inside foo() : ", y) # uses global y since there is no local y# Variable 'y' is redefined as a localdef goo():y = 2 # redefines y in a local scopeprint ("Inside goo() : ", y)def hoo():global y #makes y global and hence, modifiabley = 3print ("Inside hoo() : ",y)# Global scopeprint ("global y : ",y)foo()print ("global y : ",y)goo()print ("global y : ",y)hoo()print ("global y : ",y)
Try it yourself
Modify the code to answer the following questions:
What happens if you remove the
globalkeyword fromhoo()?What happens if you add
global yinsidegoo()?What happens if you declare
y = 0as a local variable insidefoo()?
Key takeaways
Global access: The
globalkeyword is not needed for printing and accessing, just for modifying.Modifying global variables: Without
global, any variable inside a function is treated as local, even if it has the same name as a global variable.Practical use: The
globalkeyword is useful when multiple functions need to work with the same variable, like a shared task counter or settings.Best practice: Use
globalsparingly. Overusing global variables can make your code harder to debug and maintain.
Become a Python developer with our comprehensive learning path!
Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.
This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
When should I use the global keyword in Python?
Can I use the global keyword to create a global variable inside a function?
Is it bad practice to use global variables in Python?
What are the implications of using global with closures or in recursive functions?
Free Resources