To count the number of vowels in a user-entered string
Expt. No.12
Page No.24
Count vowels in a string
Aim
To write a Python program that counts the vowels in a string entered by the user.
Concepts used
Algorithm
- Input a string and set count = 0.
- For each character, if it is in "aeiouAEIOU", add 1 to count.
- Display the count.
Program
# Count the vowels in a string text = input("Enter a string: ")count = 0for ch in text: if ch in "aeiouAEIOU": count = count + 1print("Number of vowels:", count)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python count_vowels.py
Enter a string: Informatics Practices
Number of vowels: 7
✓ Printed by running this program, not typed by hand.
Result
"Informatics Practices" has 7 vowels: I, o, a, i in "Informatics" and a, i, e in "Practices".
Viva voce: what the examiner may ask
01What does for ch in text do?
It takes each character of the string in turn.
02Why are uppercase vowels included in the check string?
The in test is case-sensitive, so "I" would not match "i".
03What does in return?
True or False.
Variations for the lab test
- Count each vowel separately.
- Count the consonants too.
- Display the string without its vowels.
! Common mistake Checking only "aeiou" misses the capital "I" at the start of "Informatics".