[Type B] Working with Functions – Chapter 3 Sumita Arora
Table of Contents
7. Predict the output of the following code:
Python
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)
Solution: Though, this code will result in an UnboundLocalError
because the variable a
is referenced before assignment inside the function myfunc
.
The initial print statement print("y =", y, "a =", a)
outside the function myfunc()
also executes correctly, showing y = 5
and a = 10
. However, when the myfunc()
function is called, it raises an UnboundLocalError
.
Therefore, the execution of the script stops prematurely, and the final print statement is not reached. Here’s the output in the console.
Output
y = 5 a = 10
Traceback (most recent call last):
File "example.py", line 11, in <module>
print(myfunc())
File "example.py", line 5, in myfunc
y = a
UnboundLocalError: local variable 'a' referenced before assignment