Problem: Write a Python program to count the number of vowels and consonants in a given string.

Example:

String: Pencil Programmer
Vowels: 5
Consonants: 12

To count the number of vowels and consonants in a string, we iterate using a for loop through each character of the string and check if it matches a vowel.

If yes then, we increment the vowel counter otherwise increment the consonant counter.

#define all vowels in a list
vowels = ['a', 'e', 'i', 'o', 'u']

#input a string and transform it to lower case
str = input("Enter a string: ").lower()

#define counter variable for both vowels and consonants
v_ctr = 0
c_ctr = 0

#iterate through the characters of the input string 
for x in str:
    #if character is in the vowel list,
    #update the vowel counter otherwise update consonant counter
    if x in vowels:
        v_ctr += 1
    else:
        c_ctr += 1

#output the values of the counters
print("Vowels: ", v_ctr)
print("Consonants: ", c_ctr)

Output:

Enter a string: Pencil Programmer
Vowels: 5
Consonants: 12

Enter a string: Python
Vowels: 1
Consonants: 5

In the above program, we have defined all vowels of the English alphabet in a list and use the same to check for vowels in the string.

Inside the for loop, we check whether the character (x) of the string is present in the vowels list or not.

If yes then it is a vowel, so we increment the vowel counter (v_ctr += 1) otherwise, we increment the counter of consonants (c_ctr += 1).

Finally, we output both counter’s values at the end of the program.

Leave a Reply