Write Python. Understand every error.

Open the editor

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

  1. Read the text and change it to lower case.
  2. Visit each character with a for loop.
  3. 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

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: