Editor

Python Program to Count Vowels, Consonants, Uppercase and Lowercase Letters

Beginner · Strings · CBSE class 11 practical list

This program goes through a string one character at a time and counts four things: vowels, consonants, uppercase letters and lowercase letters. Spaces, digits and punctuation are skipped, because they are not letters.

Program

count_vowels_consonants.py
text = "Hello World, Python Is Fun!" # or: text = input("Enter a string: ")
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
for ch in text:
if ch.isalpha(): # only letters are counted
if ch.lower() in "aeiou":
vowels += 1
else:
consonants += 1
if ch.isupper():
uppercase += 1
else:
lowercase += 1
print("String:", text)
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase letters:", uppercase)
print("Lowercase letters:", lowercase)
Output
String: Hello World, Python Is Fun!
Vowels: 6
Consonants: 15
Uppercase letters: 5
Lowercase letters: 16

How it works

  1. The loop looks at each character ch of the string in turn.
  2. ch.isalpha() is True only for letters, so spaces, digits and punctuation are left out of every count.
  3. ch.lower() in "aeiou" treats capital and small vowels the same, and any other letter counts as a consonant.
  4. ch.isupper() decides whether the letter goes into the uppercase count or the lowercase count.

Another way to write it

Using sum() with conditions

Using sum() with conditions
text = "Hello World, Python Is Fun!"
vowels = sum(1 for ch in text if ch.isalpha() and ch.lower() in "aeiou")
consonants = sum(1 for ch in text if ch.isalpha() and ch.lower() not in "aeiou")
uppercase = sum(1 for ch in text if ch.isupper())
lowercase = sum(1 for ch in text if ch.islower())
print("Vowels:", vowels, "| Consonants:", consonants)
print("Uppercase:", uppercase, "| Lowercase:", lowercase)
Output
Vowels: 6 | Consonants: 15
Uppercase: 5 | Lowercase: 16

Each line counts one thing in a single expression; it is shorter, but the string is scanned four times instead of once.

Try it yourself

Add a fifth counter for digits using ch.isdigit() and test it with the string "Class 11 B".

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises