Python programs · Strings
Python program to count vowels and consonants
Counting letters by type combines a loop, a membership test and a couple of string methods.
Approach
- Read the text and change it to lower case.
- Visit each character with a
forloop. - Count the vowels, then count the other letters as consonants.
The program
text = input().lower() vowels = 0 consonants = 0 for ch in text: if ch in "aeiou": vowels += 1 elif ch.isalpha(): consonants += 1 print("Vowels:", vowels) print("Consonants:", consonants)
Sample run
Input
Programming
Output
Vowels: 3 Consonants: 8
How the code works
.lower() makes the test ignore capital letters. ch in "aeiou" is true for a vowel. elif ch.isalpha() counts only letters, so spaces, digits and punctuation are skipped. A letter that is not a vowel must be a consonant. In "Programming" the vowels are o, a and i.
Try changing it
- Count each vowel separately with a dictionary.
- Count words instead of letters using
len(text.split()).
Common mistakes
- Forgetting
.lower(), so capital vowels are counted as consonants. - Counting every non-vowel character as a consonant, including spaces.