Python Program to Count the Number of Each Vowel


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In English, a vowel is a speech sound that is made with the vocal cords and with an unrestricted flow of air through the mouth. Vowels are one of two basic types of sounds in English (the other being consonants), and they are typically represented by the letters A, E, I, O, and U.


Python Code :

The below Python program to count the number of each vowel in a string:


# Take input string from user
string = input("Enter a string: ")

# Define a set of vowels
vowels = set("aeiouAEIOU")

# Initialize a dictionary to store the counts of each vowel
counts = {}.fromkeys(vowels, 0)

# Count the number of each vowel in the string
for char in string:
    if char in vowels:
        counts[char.lower()] += 1

# Display the counts of each vowel
for vowel, count in counts.items():
    print(vowel, ":", count)

Explanation:

  1. The program takes a string input from the user and stores it in the variable string.

  2. A set called vowels is defined to contain all vowel characters (both upper and lower case).

  3. A dictionary called counts is initialized using the fromkeys() method to contain all vowels as keys, and their initial counts set to 0.

  4. A for loop is used to iterate over each character in the input string. For each vowel character, the count in the counts dictionary is incremented.

  5. Finally, another for loop is used to iterate over each vowel in the counts dictionary, and display its count using the print() function.

  6. Note that the char.lower() method is used to convert uppercase vowels to lowercase, so that they can be counted together with their lowercase counterparts.

For Example:


Enter a string: Earth is Flat
I : 0
u : 0
o : 0
A : 0
i : 1
O : 0
U : 0
E : 0
a : 2
e : 1


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co