I don't understand how these recursive calls could finish

Here is my simple Python function:

def f(b):
    return b and f(b)

To me this must be an infinite loop, no matter the value of b, because b is always the same. But:

  • With f(True) I get an overflow, which is what I expected
  • When I run f(False) I get False!

I'm very curious about that.


Solution 1:

Recursion stops when b is falsey, i.e. False (or an empty string, or zero).

In some more detail,

x and y

does not evaluate y if x is False (or, as explicated above, another value which is interpreted as that when converted into a bool value, which Python calls "falsey"), as it is then impossible for y to affect the outcome of the expression. This is often called "short-circuiting".