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
1 Like
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 themyfunc
function, this line declares that the variablenum
is a global variable, meaning it refers to thenum
variable defined outside the function.num = 10
— Inside themyfunc
function, this line changes the value of the global variablenum
to 10.print(num)
— This line prints the value of the global variablenum
, which is still 1 at this point asmyfunc
hasn't been called yet.print(myfunc())
— This line calls themyfunc
function. 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 variablenum
after themyfunc
function 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)