Count Vowels Recursively
Count English vowels recursively by advancing an index. Students use a string-length base case and combine one-character contributions into a returned count.
1def count_vowels(s, index=0):2 # Base case3 if index >= len(s):4 return 056 # Check current character7 vowels = "aeiouAEIOU"8 count = 09 if s[index] in vowels:10 count = 11112 # Recurse13 return count + count_vowels(s, index + 1)1415# Test16text = input("Enter a string: ")17result = count_vowels(text)18print(f"Number of vowels: {result}")
Output
Enter a string: Hello Number of vowels: 2
In this one
- Advance an index
- Count character contributions
- Use a length base case
How it works
- 1
Return zero after the final index.
- 2
Assign a one-or-zero contribution for the current vowel test.
- 3
Add the count returned for index + 1.
Edge cases
What happens for empty text?
What happens for empty text?
The first call returns zero.
Does uppercase A count?
Does uppercase A count?
Yes. Both cases appear in the vowel string.
What's going on
The function checks s[index] against a string containing lowercase and uppercase vowels. A match contributes one; every other character contributes zero.
The next call advances index rather than slicing the input. When index reaches the length, zero ends the sum. For Sky the result is zero because y is not in this vowel set. Pending additions occupy the call stack.
What happens for empty text? The first call returns zero.
Does uppercase A count? Yes. Both cases appear in the vowel string.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What moves the scan forward?
Pick an answer to check it.
Question 2
What happens for empty text?
Pick an answer to check it.
Questions people ask
What happens for empty text?
The first call returns zero.
Does uppercase A count?
Yes. Both cases appear in the vowel string.
What moves the scan forward?
index + 1.
๐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