Count Vowels Recursively

Count vowels in a string recursively.

Logic BuildingAdvanced
Logic Building
def count_vowels(s, index=0):
    # Base case
    if index >= len(s):
        return 0
    
    # Check current character
    vowels = "aeiouAEIOU"
    count = 0
    if s[index] in vowels:
        count = 1
    
    # Recurse
    return count + count_vowels(s, index + 1)

# Test
text = input("Enter a string: ")
result = count_vowels(text)
print(f"Number of vowels: {result}")

Output

Enter a string: Hello
Number of vowels: 2

Check current character, recurse on rest.

Key Concepts:

  • Base case: index >= len(s)
  • Check if current char is vowel
  • Add 1 if vowel, recurse with index+1