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
What will be the output of following program ?
num = 1 def myfunc(): global num num = 10 return num print(num) print(myfunc()) print(num)
What will be the output of following program ?
def display(): print("Hello", end='') display() print("there!")
What is wrong with the following function definition ?
def addEm(x, y, z): return x + y + z print("the answer is", x + y + z)
Write a function namely fun that takes no parameters and always returns None.