Instagram
youtube
Facebook
Twitter

Count Occurrence of Vowels and Consonants in a String

A Python program to count how many vowels and consonants are present in a given string.

 13. Python program to count Occurrence Of Vowels & Consonants in a String.

Explanation of Code in Points:

  1. Define Function: count_vowel_consonants(string) → Counts vowels and consonants in a string.
     
  2. Store Vowels: vowels = "aeiouAEIOU" → Contains both lowercase and uppercase vowels.
     
  3. Initialize Counters: sum_of_vowels = 0, sum_of_consonants = 0 → Used to count vowels and consonants.
     
  4. Loop Through String: for char in string: → Iterates over each character in the input string.
     
  5. Check If Letter: if char.isalpha(): → Ensures only alphabetic characters are counted.
     
  6. Count Vowels: if char in vowels: → If the character is a vowel, increment sum_of_vowels.
     
  7. Count Consonants: else: → If it's not a vowel, it's a consonant, so increment sum_of_consonants.
     
  8. Return Values: return sum_of_vowels, sum_of_consonants → Returns the counts of vowels and consonants.
     
  9. Take User Input: string = input("Enter a string: ") → Prompts the user for input.
     
  10. Call Function & Store Result: vowel_count, consonant_count = count_vowel_consonants(string) → Calls the function and stores the result.
     
  11. Print Results:
     
    • print("Total vowels =", vowel_count) → Displays the total number of vowels.
       
    • print("Total consonants =", consonant_count) → Displays the total number of consonants.

 

Program:

def count_vowel_consonants(string):

    vowels = "aeiouAEIOU"

    sum_of_vowels = 0

    sum_of_consonants = 0

    for char in string:

        if char.isalpha():  # Check if the character is a letter

            if char in vowels:

                sum_of_vowels += 1

            else:

                sum_of_consonants += 1

    return sum_of_vowels, sum_of_consonants

string = input("Enter a string: ")

vowel_count, consonant_count = count_vowel_consonants(string)

print("Total vowels =", vowel_count)

print("Total consonants =", consonant_count)