-4

im having trouble figuring out how this works. can someone pls explain it to me. the code works btw.

def foo(x, y):

def goo(x, y):

    x = 2*x

    y = 3*y

    z = x+y

    print('x =', x, '; y =', y, '; z =', z)

    return z


def hoo(x, y):

    x = x//2

    y = y//3

    z = x+y

    print('x =', x, '; y =', y, '; z =', z)

    return z


z = hoo(x,y) + goo(y,x)

print('x =', x, '; y =', y, '; z =', z)

return z


x = 10

y = 20

z = 30

print('x =', x, '; y =', y, '; z =', z)

z = foo(x,y)

print('x =', x, '; y =', y, '; z =', z)
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
kattt
  • 1
  • 1
    Please format the code properly and read these guidelines on how to ask a good question: https://stackoverflow.com/help/how-to-ask – Agile_Eagle Sep 16 '18 at 09:39

1 Answers1

0

To understand how a code works, just follow the functions.

foo is called. Since integer types are immutable (wikipedia) in foo(x,y) x and y are copies of the x and y you gave as parameters.

In python expression are evaluated from left to right therefore.

First function hoo is called (same remark about parameters) the value of x and y are changed and z is computed you get ('x =', 5, '; y =', 6, '; z =', 11) and the value z (11) is returned.

Once outside hoo function x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above) . Then function goo is called. (same remark about parameters) (warning you enter y for parameter x of goo and x for parameter y of goo) the value of x and y are changed and z is computed you get ('x =', 40, '; y =', 30, '; z =', 70) and the value z (70) is returned.

Once outside goo function x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above).

The sum function between the two values returned by hoo and goo is done. z= 11 + 70. you get ('x =', 10, '; y =', 20, '; z =', 81) and z is returned.

Then outside foo function. x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above) . z is given the value of the return function foo therefore z=81

And you get ('x =', 10, '; y =', 20, '; z =', 81)

PilouPili
  • 2,601
  • 2
  • 17
  • 31