Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Product of Digits Recursively

Multiply digits with a recursive helper. Students distinguish the empty-product base case from a literal zero digit and trace short-circuiting on internal zeros.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 4 of 10
product-of-digits-recursively.py
1def product_digits(n):
2 # Base case
3 if n == 0:
4 return 1
5
6 # Recursive case
7 last_digit = n % 10
8 if last_digit == 0:
9 return 0 # Product becomes 0
10 return last_digit * product_digits(n // 10)
11
12# Test
13num = int(input("Enter a number: "))
14result = 0 if num == 0 else product_digits(abs(num))
15print(f"Product of digits: {result}")

Output

Enter a number: 234
Product of digits: 24

In this one

  • Use an empty-product identity
  • Short-circuit on a zero digit
  • Handle zero in the caller

How it works

  1. 1

    Return zero directly for literal input zero.

  2. 2

    For other magnitudes, multiply digits through recursive returns.

  3. 3

    Return one for exhaustion or zero for a zero digit.

Edge cases

What should input zero produce?

What should input zero produce?

Zero, handled separately from the helper's empty remainder.

What happens for 203?

What happens for 203?

The zero digit forces the product to zero.

What's going on

The helper returns one when there are no remaining digits, allowing the final multiplication to keep its value. A zero last digit returns zero immediately.

For 234, pending products combine four, three, and two into twenty-four. A literal input zero needs a caller-level zero result instead of the empty-product identity. abs removes negative signs; ordinary recursive calls still occupy Python's call stack.

What should input zero produce? Zero, handled separately from the helper's empty remainder.

What happens for 203? The zero digit forces the product to zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why does the terminal helper return one?

Pick an answer to check it.

Question 2

What should input zero produce?

Pick an answer to check it.

Questions people ask

What should input zero produce?

Zero, handled separately from the helper's empty remainder.

What happens for 203?

The zero digit forces the product to zero.

Why does the terminal helper return one?

It must not erase the final nonzero digit.