Chapter 6: Problem 31
Can a function have a local variable with the same name as a global variable?
Short Answer
Expert verified
Explain with an example.**
Yes, a function can have a local variable with the same name as a global variable. When this happens, the local variable is said to "shadow" or "mask" the global variable within the scope of that function.
For example, consider a global variable `x = 10`. Now, let's declare a function with a local variable named `x` as well:
```python
def example_function():
x = 5
print("Inside function, x =", x)
```
In this case, the local variable `x` within the function `example_function` is shadowing the global variable `x`. When we call this function, it will print "Inside function, x = 5", while the global variable `x` will remain unchanged at 10.