← Back

Home â€ē Python programs

Count Vowels in a String in Python

⤇⤏āĨ‡ Hindi ā¤ŽāĨ‡ā¤‚ ā¤Ēā¤ĸā¤ŧāĨ‡ā¤‚

Problem statement

Count how many vowels (a, e, i, o, u) appear in a sentence, treating uppercase and lowercase the same.

Approach 1: simple loop

Walk the string character by character and raise a counter whenever the character is one of the five vowels. The in operator checks membership in the vowel string directly.

text = "python programming"
vowels = "aeiou"
count = 0

for ch in text:
    if ch in vowels:
        count = count + 1

print(count)
# Output: 4

Every character gets exactly one question: "are you one of a, e, i, o, u?" The counter remembers how many times the answer was yes.

Approach 2: reusable function

Make it a function and normalise the case first — .lower() turns A into a so the uppercase vowels are counted without listing them twice.

def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    return count

print(count_vowels("PYTHON"))              # 1
print(count_vowels("Education"))           # 5
print(count_vowels("xyz"))                 # 0

The function returns the number instead of printing it, so it can be used inside bigger programs — reports, filters, scoring.

Approach 3: Pythonic alternative

Python can count in one expression: sum() over a generator that yields 1 for each vowel. The condition is the same as before — only the bookkeeping is gone.

text = "python programming"

print(sum(1 for ch in text.lower() if ch in "aeiou"))   # 4
print(sum(text.lower().count(v) for v in "aeiou"))      # 4 — counts per vowel

The second form counts each vowel separately and adds the five results — handy when you want the breakdown per letter rather than the total.

Dry run

Trace "hello": h — not a vowel, counter stays 0. e — vowel, counter 1. l — no. l — no. o — vowel, counter 2. Final answer: 2. With "PYTHON" and the function version, the string first becomes "python"; only o passes the test, so the answer is 1 — the capital letters changed nothing, which is exactly what .lower() is for. One row per character is all a dry run ever needs.

Common errors

Practice on PyDebug

Turn the idea into a debugging habit with these free browser exercises: