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: 4Every 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")) # 0The 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
- Forgetting uppercase â
'A' in "aeiou"is False, so capitalised words undercount. Normalise with.lower()first. - Counting with
text.count(vowels)âcount()hunts for the whole substring "aeiou", not the individual letters. - Using
if ch == "aeiou"â one character can never equal a five-character string; membership needsin. - Printing inside the loop â the running count spams the screen instead of the final answer.
- Assuming spaces or punctuation break the loop â they simply fail the vowel test and move on.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: