[Solved] How python recursive function works in terms of addition? [closed]


What happens here?

You originally call the function with k = 7.

  1. The function sees that the given value k = 7 is > 0 and thus calculates 7 + the result of the function if called with 6.
    In order to determine the latter, it calls itself with k = 6.

  2. The function sees that the given value k = 6 is > 0 and thus calculates 6 + the result of the function if called with 5.
    In order to determine the latter, it calls itself with k = 5.

  3. The function sees that the given value k = 5 is > 0 and thus calculates 5 + the result of the function if called with 4.
    In order to determine the latter, it calls itself with k = 4.

  4. The function sees that the given value k = 4 is > 0 and thus calculates 4 + the result of the function if called with 3.
    In order to determine the latter, it calls itself with k = 3.

  5. The function sees that the given value k = 3 is > 0 and thus calculates 3 + the result of the function if called with 2.
    In order to determine the latter, it calls itself with k = 2.

  6. The function sees that the given value k = 2 is > 0 and thus calculates 2 + the result of the function if called with 1.
    In order to determine the latter, it calls itself with k = 1.

  7. The function sees that the given value k = 1 is > 0 and thus calculates 1 + the result of the function if called with 0.
    In order to determine the latter, it calls itself with k = 0.

  8. The function sees that the given value k = 0 is not > 0 and thus returns 0.

So

  • the function run in point 7 calculates 1 + 0 = 1.
  • the function run in point 6 calculates 2 + 1 = 3.
  • the function run in point 5 calculates 3 + 3 = 6.
  • the function run in point 4 calculates 4 + 6 = 10.
  • the function run in point 3 calculates 5 + 10 = 15.
  • the function run in point 2 calculates 6 + 15 = 21.
  • the function run in point 1 calculates 7 + 21 = 28.

In the end, the 28 is returned by the “original function call”, but discarded. You see it only because of the print(result) inside the function.

There is nothing different to the principle compared to any other recursive function call.

3

solved How python recursive function works in terms of addition? [closed]