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.
1def product_digits(n):2 # Base case3 if n == 0:4 return 156 # Recursive case7 last_digit = n % 108 if last_digit == 0:9 return 0 # Product becomes 010 return last_digit * product_digits(n // 10)1112# Test13num = 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
Return zero directly for literal input zero.
- 2
For other magnitudes, multiply digits through recursive returns.
- 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.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum