Computer Science
What will be the output of following program ?
num = 1
def myfunc():
global num
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer
1
10
10
Working
num = 1— This line assigns the value 1 to the global variablenum.def myfunc()— This line defines a function namedmyfunc.print(num)— This line prints the value of the global variablenum, which is 1.print(myfunc())— This line calls themyfuncfunction. Inside themyfuncfunction, the value 10 is assigned to the global variablenum. Because of the global keyword used earlier, this assignment modifies the value of the global variablenumto 10. The function then returns 10.print(num)— This line prints the value of the global variablenumagain, which is still 1.
Related Questions
What will be the output of following program ?
num = 1 def myfunc(): return num print(num) print(myfunc()) print(num)What will be the output of following program ?
num = 1 def myfunc(): 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!")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)