Thursday , September 19 2024

What is the output of the following snippet? def fun(x): global y y = x * x return y fun(2) print(y)

Questions BankCategory: Python Essentials 1What is the output of the following snippet? def fun(x): global y y = x * x return y fun(2) print(y)
What is the output of the following snippet?

def fun(x):
    global y
    y = x * x
    return y
 
 
fun(2)
print(y)
  • None
  • 2
  • 4
  • the code will cause a runtime error

Explanation: Let’s analyze the code:

  • the fun function is invoked with the integer 2 as its argument,
  • the fun function makes the y variable a global variable, which can be used both inside and outside of the function,
  • the operation y = 2 * 2 is performed, and the answer is the integer 4,
  • the function returns the y variable value,
  • the print(y) instruction prints the integer 4 on the console.

More Questions: Python Essentials 1 – Module 4 Test