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
  1. num = 1 — This line assigns the value 1 to the global variable num.
  2. def myfunc(): — This line defines a function named myfunc.
  3. global num — Inside the myfunc function, this line declares that the variable num is a global variable, meaning it refers to the num variable defined outside the function.
  4. num = 10 — Inside the myfunc function, this line changes the value of the global variable num to 10.
  5. print(num) — This line prints the value of the global variable num, which is still 1 at this point as myfunc hasn't been called yet.
  6. print(myfunc()) — This line calls the myfunc function. However, since the function doesn't have a return statement, it implicitly returns None, which is then printed.
  7. print(num) — Finally, this line prints the value of the global variable num after the myfunc function has been called, which is now 10 due to the assignment inside the function.

Answered By

1 Like


Related Questions