Python Program to Count Vowels & Consonants in a String

In this tutorial, we will discuss a Python program to count the vowels & consonants in a string.

Related: Python program for Merge Sort

Program code for counting the number of vowels & consonants in a string in Python

# Count Vowels and Consonants in a String in Python
def count_vowels_and_consonants(string):
    vowels = 'aeiouAEIOU'
    vowel_count = 0
    consonant_count = 0
    for char in string:
        if char.isalpha():
            if char in vowels:
                vowel_count += 1
            else:
                consonant_count += 1
    return vowel_count, consonant_count

input_string = input("Enter a string: ")
vowels, consonants = count_vowels_and_consonants(input_string)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")

Explanation

  1. Function Definition: The count_vowels_and_consonants function takes a string as input and returns the count of vowels and consonants in the string.
  2. Main Program: The program prompts the user to enter a string and then counts the number of vowels and consonants using the count_vowels_and_consonants function and prints the result.

Output

Python Program to Count Vowels & Consonants in a String

  • When you run the above program, it will prompt you to enter a string.
  • After entering the string, it will count the number of vowels and consonants and print the result.

Conclusion

  • In this tutorial, we learned how to count the number of vowels and consonants in a string using a Python program.
  • Understanding this concept is essential for text analysis and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *