Q1: Demonstrate the use of a local variable
def display_number():
num = 10 # Local variable
print("Inside function:", num)
display_number()
try:
print("Outside function:", num)
except NameError as e:
print("Error:", e)
Inside function: 10
Error: name 'num' is not defined
Q2: Demonstrate the use of a global variable
x = 20 # Global variable
def show_global():
print("The value of x is", x)
show_global()
The value of x is 20
Q3: Differentiate between global and local variables
x = 100 # Global variable
def test_scope():
x = 50 # Local variable (shadows the global)
print("Inside function:", x)
test_scope()
print("Outside function:", x)
Inside function: 50
Outside function: 100
Q4: Modify a global variable inside a function
counter = 0 # Global variable
def increase():
global counter
counter += 1
print("Updated counter:", counter)
increase()
increase()
Updated counter: 1
Updated counter: 2
Q5: Use both global and local variables in a program
total = 0 # Global variable
def add_numbers(a, b):
global total
sum = a + b # Local variable
total += sum
print("Updated total:", total)
add_numbers(5, 10)
add_numbers(3, 7)
Updated total: 15
Updated total: 25
Q6: What will be the output and explanation