QuestionSeptember 18, 2025

6. Write a function that demonstrates variable scope by using a local and global variable with the same name.

6. Write a function that demonstrates variable scope by using a local and global variable with the same name.
6. Write a function that demonstrates variable scope by using a local and global variable with
the same name.

Solution
4.4(311 votes)

Answer

```python x = 10 # Global variable def demo_scope(): x = 20 # Local variable (shadows global) print("Inside function, x =", x) demo_scope() print("Outside function, x =", x) ``` Explanation 1. Define a global variable Create a variable outside any function, e.g., x = 10. 2. Define a function with a local variable of the same name Inside the function, declare a local variable x = 20 and print its value. 3. Print global variable outside the function After calling the function, print the global variable to show it remains unchanged.

Explanation

1. Define a global variable<br /> Create a variable outside any function, e.g., $x = 10$.<br />2. Define a function with a local variable of the same name<br /> Inside the function, declare a local variable $x = 20$ and print its value.<br />3. Print global variable outside the function<br /> After calling the function, print the global variable to show it remains unchanged.
Click to rate:

Similar Questions