How to Count Vowels in Python: A Line-by-Line Guide for Beginners
Vowel Counter Program
This program is designed to take any text provided by a user and count how many times vowels appear in it. In the English language, the standard vowels are A, E, I, O, and U.
The program works by converting the input text to lowercase to ensure it doesn't miss any capital letters. It then loops through each character, checks if that character belongs to the set of vowels, and keeps a running tally. This is an essential foundational exercise for training, as it demonstrates core programming concepts such as string manipulation, loops, conditional logic, and counters.
Python Source Code
Every line is commented below to explain its exact role in the execution flow.
# This program prompts a user for a string and counts the total number of vowels (a, e, i, o, u) in it.
# Prompt the user to type a string and store that input into a variable named user_string
user_string = input("Enter a string: ")
# Define a collection of all lowercase vowels to check our characters against
vowels = "aeiou"
# Initialize a counter variable to 0 to keep track of the total number of vowels found
vowel_count = 0
# Convert the entire user string to lowercase and loop through each character one by one
for char in user_string.lower():
# Check if the current character exists inside our defined string of vowels
if char in vowels:
# Increment the counter by 1 if the character is indeed a vowel
vowel_count += 1
# Output the final result to the user by printing the accumulated count
print("Number of vowels:", vowel_count)
Sample Execution (Inputs & Outputs)
Below are test cases illustrating how the program handles different types of text inputs, including mixed cases and sentences without vowels.
| Test Case | Sample User Input | Program Output | Explanation |
|---|---|---|---|
| 1. Standard Word | Python |
Number of vowels: 1 |
Only "o" is counted. |
| 2. Mixed Casing | Education |
Number of vowels: 5 |
Contains all 5 vowels (E, d, u, c, a, t, i, o, n). Works perfectly despite the capital "E". |
| 3. Full Sentence | Hello World! |
Number of vowels: 3 |
Counts "e", "o", and "o". Spaces and punctuation are safely ignored. |
| 4. No Vowels | Rhythm fly |
Number of vowels: 0 |
"y" is not included in the standard vowel set, so it returns zero. |
Comments
Post a Comment