[go: up one dir, main page]

0% found this document useful (0 votes)
13 views3 pages

Untitled 102

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Untitled 102

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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

x = 25

def modify():
# This will throw an error because Python treats x as local,
# but it's used before it's assigned.
try:
x = x + 5
print("Inside:", x)
except UnboundLocalError as e:
print("Error:", e)

modify()
print("Outside:", x)
x = 25

def modify():
global x
x = x + 5
print("Inside:", x)

modify()
print("Outside:", x)
Error: cannot access local variable 'x' where it is not associated
with a value
Outside: 25
Inside: 30
Outside: 30

Q7: Function that reads a global variable but doesn't modify it

college = "XYZ College" # Global variable

def print_college():
print("College name is:", college)

print_college()

College name is: XYZ College

Q8: Function using both local and global variables in a calculation

base = 100 # Global variable

def calculate_bonus(score):
bonus = score * 10 # Local variable
return base + bonus

print("Total with bonus:", calculate_bonus(5))


print("Total with bonus:", calculate_bonus(8))

Total with bonus: 150


Total with bonus: 180

You might also like