If a variable has the same name locally and globally, what happens
Local vs global variables in Python: Name conflict
If a variable has the same name both locally (inside a function) and globally (outside the function), Python will prioritize the local variable over the global one when accessed inside the function.
When a variable is referenced inside a function, Python searches for a local variable with that name first. If it finds a local variable, it will use its value, even if there is a global variable with the same name.
Example:?
# Declare a global variable
global_var = 200
def test_function():
# This is a local variable with the same name as the global variable
global_var = 500
print("Inside the function:", global_var)
test_function() # Output: Inside the function: 500
# Output: Outside the function: 200
# (global_var remains unchanged)
print("Outside the function:", global_var)
In the example above, the function "test_function()" defines a local variable 'global_var' with a value of 500. When we print the value of 'global_var' inside the function, it uses the value of the local variable (500). However, when we print the value of 'global_var' outside the function, it uses the value of the global variable (200), as the local variable is no longer in scope.
To modify the global variable from within the function, we can use the "global" keyword. Here is the example:
# Declare a global variable
global_var = 200
def test_function():
# This is a local variable with the same name as the global variable
global global_var
global_var = 500
print("Inside the function:", global_var)
test_function() # Output: Inside the function: 500
# Output: Outside the function: 500 (global_var changed)
print("Outside the function:", global_var)
Output:
Inside the function: 500 Outside the function: 500
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/if-a-variable-has-the-same-name-locally-and-globally-what-happens.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics