Editor

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 lesson

Write 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 1
  • count_digits(5) returns 1
  • count_digits(123) returns 3
  • count_digits(99999) returns 5
  • Hint: 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

    All Python exercises · 50 practice problems · Functions quiz