Computer Science
What will be the output of the following program?
num = 1
def myfunc():
global num
num = 10
print (num)
print (myfunc())
print (num)
Python
Python Functions
3 Likes
Answer
1
None
10
Working
num = 1— This line assigns the value 1 to the global variablenum.def myfunc():— This line defines a function namedmyfunc.global num— Inside themyfuncfunction, this line declares that the variablenumis a global variable, meaning it refers to thenumvariable defined outside the function.num = 10— Inside themyfuncfunction, this line changes the value of the global variablenumto 10.print(num)— This line prints the value of the global variablenum, which is still 1 at this point asmyfunchasn't been called yet.print(myfunc())— This line calls themyfuncfunction. However, since the function doesn't have a return statement, it implicitly returns None, which is then printed.print(num)— Finally, this line prints the value of the global variablenumafter themyfuncfunction has been called, which is now 10 due to the assignment inside the function.
Answered By
1 Like
Related Questions
What are variables ? How are they important for a program ?
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 the following program?
def display(): print ("Hello",) display() print("bye!")What is wrong with the following function definition ?
def addEm(x, y, z): return x + y + z print("the answer is", x + y + z)