This article explains variable scoping in Python, focusing on local and global variables and the use of the global keyword.
In this lesson, we explore how variable scoping works in Python. By understanding the difference between local and global variables, you can write clearer and more effective code. This guide covers how variables declared inside a function are confined to that function, and when the global keyword is required.
Variables defined inside a function are local to that function. They cannot be accessed outside of the function’s scope. Consider the following example:
Copy
Ask AI
def input_number(): result = int(input("Enter a number: ")) * 100 return result
Here, the variable result is local to the input_number function. Trying to reference result elsewhere in your code will lead to an error because its scope is strictly within the function.
It is possible to use variables that are declared outside a function (global variables) within the function body. However, if a variable with the same name exists both globally and locally, the local variable will take precedence—a concept known as shadowing.
By default, variables declared inside a function are not accessible outside of it. To modify a global variable within a function, you must declare it as global using the global keyword.
Declaring a variable as global allows you to modify it inside a function, making it accessible in the global scope after the function call.
Here’s an example:
Copy
Ask AI
num = 100def input_number(): global own_num own_num = 50 # 'own_num' is now a global variable result = int(input("Enter a number: ")) * own_num return result
After calling input_number(), you can access the variable own_num from the global scope:
Copy
Ask AI
>>> input_number()2 # Example output based on user input>>> print(own_num)50
Now that you understand local and global variable scopes in Python, try practicing these concepts with some hands-on exercises. Experiment with variable shadowing and the global keyword to see how scope affects your code.For further learning, check out the following: