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