Computer Science
What will be the output of following program ?
num = 1
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)
Answer
1
10
1
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. Insidemyfuncfunction,num = 10defines a local variablenumand assigns it the value of10which is then returned by the function. It is important to note that the value of global variablenumis still 1 asnumofmyfuncis local to it and different from global variablenum.print(num)— This line prints the value of the global variablenum, which is still 1.
Related Questions
What will the following function print when called ?
def addEm(x, y, z): return x + y + z print(x + y + z)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(): 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!")