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
    elif x != ' ':
        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.

This Post Has 3 Comments

  1. priya

    According to your code, if there are any spaces in the input it is also counted as consonants, but i want a without count spaces, what to do

    1. Adarsh Kumar

      code updated! I have changed the else to elif.

  2. Marc

    Hello, the change from else to elif doesn’t shinely work.

    I would have another problem yet : how would you count the nb of occurrences of each letter in a string, to put in a dictionnary
    so as for “Hello world”, it’d return :
    {“H”:1, “e”:1, “l”:3, “o”:2, “W”:1, “r”:1, “d”:1}

Leave a Reply to Marc Cancel reply