Count Vowels & Consonants Recursively
Count vowels and consonants recursively with carried totals. Students filter letters, lowercase each character, and return two values at the stopping index.
1def count_vc(s, index=0, vowels=0, consonants=0):2 # Base case3 if index >= len(s):4 return vowels, consonants56 # Check current character7 char = s[index].lower()8 if char.isalpha():9 if char in 'aeiou':10 vowels += 111 else:12 consonants += 11314 # Recurse15 return count_vc(s, index + 1, vowels, consonants)1617# Test18text = input("Enter a string: ")19v, c = count_vc(text)20print(f"Vowels: {v}, Consonants: {c}")
Output
Enter a string: Hello Vowels: 2, Consonants: 3
In this one
- Carry two counters
- Filter letters before vowels
- Unpack a returned tuple
How it works
- 1
Inspect the lowercase character at index.
- 2
Increment the appropriate counter only for letters.
- 3
Advance the index, then return both counters at the end.
Edge cases
Are digits counted as consonants?
Are digits counted as consonants?
No. They fail isalpha.
What does empty text return?
What does empty text return?
The pair zero, zero.
What's going on
The helper carries index, vowels, and consonants as arguments. isalpha excludes digits and punctuation before a letter is classified.
English vowels increase vowels; other alphabetic characters increase consonants under this code's rule. At the end, a tuple returns both totals for unpacking into v and c. The index advances on every character, and active calls occupy the stack.
Are digits counted as consonants? No. They fail isalpha.
What does empty text return? The pair zero, zero.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why return two values?
Pick an answer to check it.
Question 2
Are digits counted as consonants?
Pick an answer to check it.
Questions people ask
Are digits counted as consonants?
No. They fail isalpha.
What does empty text return?
The pair zero, zero.
Why return two values?
Both counters are needed for the final message.
๐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