Mutual Recursion for Even/Odd Check in Python

Implements even and odd checks using two functions that call each other recursively, demonstrating base cases and alternating calls.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

13 lines
Python 3.9+
def is_even(n):
    if n == 0:
        return True
    return is_odd(n - 1)

def is_odd(n):
    if n == 0:
        return False
    return is_even(n - 1)

if __name__ == "__main__":
    for num in range(0, 11):
        print(f"{num}: even={is_even(num)}, odd={is_odd(num)}")

Output

stdout
0: even=True, odd=False
1: even=False, odd=True
2: even=True, odd=False
3: even=False, odd=True
4: even=True, odd=False
5: even=False, odd=True
6: even=True, odd=False
7: even=False, odd=True
8: even=True, odd=False
9: even=False, odd=True
10: even=True, odd=False

How it works

Mutual recursion works because each function reduces n by 1 and delegates to the other, so the two functions alternate calls as n decreases. The base cases stop the chain at n == 0, where is_even returns True and is_odd returns False, matching the mathematical definition. This pattern is a clear illustration of how recursion can be split across multiple functions. Note that for large n, this will hit Python's recursion limit (default 1000), so it is best used for educational purposes or small inputs.

Common mistakes

  • Swapping the base-case return values (True for is_odd or False for is_even)
  • Forgetting to decrement n, causing infinite recursion
  • Using modulo (%) as a shortcut instead of exploring the recursive design

Variations

  1. Use a single is_even function with `not is_even(n - 1)` instead of a separate is_odd
  2. Switch to iterative loop with two booleans for O(1) space and faster performance

Real-world use cases

  • Teaching recursion and algorithm design in computer science courses.
  • Demonstrating indirect recursion in language interpreter design where parses alternate rules.
  • Modeling turn-based state transitions where each state delegates to the next state.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.