Go through the text one character at a time and add 1 to a counter each time the character is a vowel.
The program
python
text = input("Enter a sentence: ") vowels = "aeiou" count = 0 for ch in text.lower(): if ch in vowels: count += 1 print(f"Number of vowels: {count}")
Typed in this example: Programming in Python is fun. Press Run to type your own.
output
Enter a sentence: Programming in Python is fun Number of vowels: 7
How it works
ch in vowelsisTruewhen the character appears in the string"aeiou". Theinoperator checks whether one string is inside another.text.lower()turns capital letters into small ones first. Without it, a capital vowel such as the "A" in "Ada" would not be counted.- Spaces, digits and punctuation are not in
"aeiou", so they are skipped.
Count each vowel separately
A dictionary can hold one counter per vowel. Start each one at 0, then add to the right one:
python
text = "Grace Hopper wrote the first compiler" counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0} for ch in text.lower(): if ch in counts: counts[ch] += 1 for vowel, n in counts.items(): print(vowel, n)
output
a 1 e 5 i 2 o 3 u 0
ch in counts checks the keys of the dictionary, so it works the same way as ch in "aeiou".