KnowledgeBoat Logo

Computer Science

Predict the output of the following code :

a = 10
y = 5
def myfunc(): 
    y = a
    a = 2
    print("y =", y, "a =", a) 
    print("a + y =", a + y) 
    return a + y
print("y =", y, "a =", a)
print(myfunc())  
print("y =", y, "a =", a)

Python

Python Functions

15 Likes

Answer

The code raises an error when executed.

Working

In the provided code, the global variables a and y are initialized to 10 and 5, respectively. Inside the myfunc function, the line a = 2 suggests that a is a local variable of myfunc. But the line before it, y = a is trying to assign the value of local variable a to local variable y even before local variable a is defined. Therefore, this code raises an UnboundLocalError.

Answered By

4 Likes


Related Questions