Computer Science

Predict the output of the following code:

a = 10
y = 5
def myfunc (a) :
    y = a
    a = 2
    print ("y=",y, "a=", a) 
    print ("a+y", a + y) 
    return a + y
print ("y=",y, "a=", a) 
print (myfunc (a))
print ("y=", y, "a=", a)

Python

Python Functions

2 Likes

Answer

y= 5 a= 10
y= 10 a= 2
a+y 12
12
y= 5 a= 10
Working
  1. a = 10 — This line assigns the value 10 to the global variable a.
  2. y = 5 — This line assigns the value 5 to the global variable y.
  3. def myfunc(a): — This line defines a function named myfunc that takes a parameter a.
  4. y = a — This line assigns the value of the parameter a (which is 10) to the local variable y within the function.
  5. a = 2 — This line assigns the value 2 to the local variable a within the function, effectively shadowing the global variable a.
  6. print("y=", y, "a=", a) — This line prints the values of the local variables y and a within the function.
  7. print("a+y", a + y) — This line prints the sum of the local variables a and y within the function.
  8. return a + y — This line returns the sum of the local variables a and y within the function.
  9. print("y=", y, "a=", a) — This line prints the values of the global variables y and a outside the function.
  10. print(myfunc(a)) — This line calls the myfunc function with the value of the global variable a (which is 10) as an argument and prints the returned value.
  11. print("y=", y, "a=", a) — This line prints the values of the global variables y and a again.

Answered By

1 Like


Related Questions