Count Digits Recursively
Advanced · Write the code · from Python Recursion: How It Works, When to Use It, and Examples
From the lesson: Python Recursion: How It Works, When to Use It, and Examples
Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.
Read the lessonWrite a recursive function called count_digits that takes a non-negative integer and returns the number of digits it has.
For example:
count_digits(0) returns 1count_digits(5) returns 1count_digits(123) returns 3count_digits(99999) returns 5Hint: dividing by 10 using // removes the last digit.
Print the results for 0, 5, 123, and 99999 on separate lines.
def count_digits(n):
# Your code here
pass
print(count_digits(0))
print(count_digits(5))
print(count_digits(123))
print(count_digits(99999))
More Recursion exercises
- Predict Recursive OutputBeginner
- Recursive Sum 1 to NBeginner
- Fix the Broken Power FunctionIntermediate
- Recursive FibonacciIntermediate
- Reverse a String RecursivelyIntermediate
All Python exercises · 50 practice problems · Functions quiz