Count Digits Recursively
Count integer digits using recursive floor division. Students trace one count per decimal position and separate zero input from the helper's empty remainder.
1def count_digits(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 return 1 + count_digits(n // 10)89# Test10num = int(input("Enter a number: "))11result = 1 if num == 0 else count_digits(abs(num))12print(f"Number of digits: {result}")
Output
Enter a number: 12345 Number of digits: 5
In this one
- Count one digit per call
- Separate zero from exhaustion
- Preserve a neutral base case
How it works
- 1
Choose one directly for literal input zero.
- 2
Otherwise call the helper on abs(num).
- 3
Return one plus the smaller digit count until exhaustion.
Edge cases
How many digits should input zero report?
How many digits should input zero report?
One, handled outside the empty-remainder base case.
Why not make every terminal return one?
Why not make every terminal return one?
That would add an extra position to nonzero numbers.
What's going on
The helper returns zero when no positive positions remain. Otherwise it counts one position and requests the count of n // 10.
For 405, the returns combine into three. The outer zero input needs its own one-digit result; changing the helper's terminal value would overcount every other input. abs removes a sign before the recursive calls occupy the call stack.
How many digits should input zero report? One, handled outside the empty-remainder base case.
Why not make every terminal return one? That would add an extra position to nonzero numbers.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does the recursive step add?
Pick an answer to check it.
Question 2
How many digits should input zero report?
Pick an answer to check it.
Questions people ask
How many digits should input zero report?
One, handled outside the empty-remainder base case.
Why not make every terminal return one?
That would add an extra position to nonzero numbers.
What does the recursive step add?
One 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