Hello. The textbook provides a mental experiment:

What will this code return?

def fib(x): if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) print(fib(4)) 

The code returns:

five

But after 4 iterations, 'x' takes the value 1! Why does the return fail and the unit does not return, completing the function?

  • And what, for a python there are no debuggers? Then print the x values ​​in the process and see for yourself. - PinkTux
  • There is a debugger. At 4 iterations, it shows that the argument passed to the function is 1. - Badalamenti
  • Hence, in this case, the function exits. But not the end of the recursion. - PinkTux
  • But why the function does not complete on 'return 1'? - Badalamenti
  • one

2 answers 2

Because in the first iteration if is not executed. When the else block starts to be executed, the first in the return code works no longer on print, which waits for a value outside the function, but on a call from the else block.

Thus, the string return 1 can never return a value to print.

Step-by-step execution can be viewed here . Many thanks to jfs for the link to a useful resource for all newbies.

    Such recursion is called cascade recursion. Try to paint using so-called forms. I put an example of how to lay out one of the examples on the forms. this is exactly this example (the function itself is written in haskell)

    By the way, it became much easier for me to understand recursion after I figured out haskell with it. Therefore, I recommend