Python coding practice

Implement count_vowels(s)

Write a recursive Python function that counts the number of vowels (a, e, i, o, u — both upper and lower case) in a string. This uses the same string-slicing technique shown for length(s) in the tutorial.

The problem

Check whether the first character is a vowel, then recurse on the remaining string (s[1:]). Add 1 if it is a vowel, 0 if it is not. Stop when the string is empty.

count_vowels("hello")
s[0] = "h" → not a vowel, 0 + count_vowels("ello")
s[0] = "e" → vowel, 1 + count_vowels("llo")
s[0] = "l" → not a vowel, 0 + count_vowels("lo")
s[0] = "l" → not a vowel, 0 + count_vowels("o")
s[0] = "o" → vowel, 1 + count_vowels("")
"" → base case → 0
Result: 0+1+0+0+1+0 = 2

Your function must pass these tests:

  • count_vowels("")0
  • count_vowels("sky")0
  • count_vowels("hello")2
  • count_vowels("recursion")4
  • count_vowels("aeiou")5

Write your solution below, then click Run Tests:

Advertisement

Hints

Hint 1 — Using the vowels variable

The stub already defines vowels = "aeiouAEIOU". You can check membership with s[0] in vowels, which returns True or False.

Hint 2 — Conditional with recursion

You need one return statement. The value returned is either 1 + count_vowels(s[1:]) (when s[0] is a vowel) or count_vowels(s[1:]) (when it is not). A ternary expression or an if/else both work.

Hint 3 — Full solution
def count_vowels(s):
    vowels = "aeiouAEIOU"
    if not s:
        return 0
    if s[0] in vowels:
        return 1 + count_vowels(s[1:])
    return count_vowels(s[1:])

More coding problems