poly_purple - 3 months ago 22
Python Question

# Understanding recursive odd/even functions

I'm currently studying python from http://www.sololearn.com/Play/Python and I'm having trouble understanding why this code works.

``````def is_even(x):
if x == 0:
return True

else:
return is_odd(x-1)

def is_odd(x):
return not is_even(x)

print(is_odd(1))
``````

I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.

`is_even'`s base case resolves to `True`. Since `is_odd(x)` returns `not is_even(x)`, the value `True` will be a part of the expression returned by `is_odd`. The question is how many times will that `True` value be negated. By tracing the calls you can see it will be negated an even number of times, and hence "retain" its truthiness, when `x` is odd [e.g.: `x=3` ==> `(not (not (not (not True))))` == `True`] and an odd number of times, and hence "lose" its truthiness, when `x` is even [e.g.: `x=2` ==> `(not (not (not True)))` == `False`]. There's probably some term from logic that names this general property of multiple negation.

Source (Stackoverflow)