In Python, local and global variables play a crucial role in programming. Understanding how local and global variables work in functions is essential for writing modular and efficient code. In this tutorial we will discuss the concept of local and global variables in functions, including their declaration, scope, and best practices.
A local variable is a variable that is either declared within a function or is a parameter of that function. These variables are called local because they are only accessible and valid within the specific function or block of code where they are declared. Local variables are not accessible from outside the function.
When a local variable is declared inside a function, it is created and assigned a value when the function is called or executed. The variable remains in memory as long as the function is running, and it is destroyed once the function finishes its execution.
Here's an example:
def calculate_sum(a, b):
# Local variable declaration
result = a + b
print("The sum is:", result)
calculate_sum(5, 3)
The sum is: 8
In this example, the function calculate_sum
takes two parameters a
and b
. Within the function, a local variable named result
is declared and assigned the value of a + b
. This local variable result
is only accessible within the calculate_sum
function.
When the function is called with the arguments 5
and 3
(calculate_sum(5, 3)
), the local variable result
is calculated and printed, displaying the sum as 8
.
Outside of the function, the local variable result
is not accessible. If you try to access it using print(result)
, it will raise a NameError
since the variable is not defined in the global scope.
Global variables are variables that are defined outside of any function or block of code and can be accessed from anywhere in the program. They have a global scope, which means they are visible and accessible throughout the entire program. Thet are usually declared at the start of the program.
x = 100 # global variable
def f():
print("x =", x)
def b():
print("x =", x)
print("x =", x)
f()
b()
Output
x = 100 # Initial value of x x = 100 # Output from f() x = 100 # Output from b()
In this example, the variable x
is declared as a global variable outside any function or block of code. Therefore, it has a global scope and can be accessed from anywhere in the program.
Both functions f()
and b()
can access and print the value of the global variable x
because it is in their scope. This demonstrates that global variables can be accessed and used within different functions, providing a way to share data among multiple parts of the program.
Naming Conflicts: Precedence of Local Variables over Global Variables
If you declare a variable that is local to a function and has the same name as a global variable, the local variable takes precedence within the function's scope. However, outside of the function, the global variable remains unaffected.
x = 100 # global variable
def f():
x = 9 # local variable
print("x =", x)
print("x =", x)
f()
print("x =", x)
Output
x = 100 x = 9 x = 100
In this example, a global variable x
is defined with an initial value of 100. Inside the function f()
, a local variable x
is declared with a value of 9. When f()
is called, it prints the value of the local variable x
(9).
Outside the function, when print("x =", x)
is executed, it accesses the global variable x
(100) because the local variable's scope is limited to the function. Therefore, the output displays x = 100
.
Accessing and Modifying Global Variables in Python
If you want to access or modify a global variable inside a function, you need to use the global
keyword.
x = 100
def f():
global x
x = 9
print("x =", x)
print("x =", x)
f()
print("x =", x)
Output:
x = 100
x = 9
x = 9
In this example, the global variable x
is initially set to 100. Inside the function f()
, the global
keyword is used to indicate that we want to access and modify the global variable x
. It is then assigned a new value of 9 and printed, resulting in x = 9
.
Outside the function, when print("x =", x)
is executed, it accesses the modified global variable x
, which is still 9. Therefore, the final output displays x = 9
.
Common Pitfalls and Error Cases:
It's important to keep in mind the following points to avoid errors when using the global
keyword:
global
statement should be declared before assigning a value to the variable within the function.global
will create a new local variable instead of modifying the global variable.Prefer Local Variables:
Limit the Use of Global Variables:
Declare Variables in the Smallest Scope Necessary:
Use Meaningful Variable Names:
Use Function Parameters and Return Values:
Use Local Variables for Temporary Storage: