Python Program to Count Vowels and Consonants in a String

1. Introduction

Vowels in the English alphabet are 'a', 'e', 'i', 'o', 'u' (sometimes 'y' is included). All other alphabetic characters are considered consonants. The task is to iterate over a string and count how many of each category are present.

2. Program Steps

1. Initialize a string variable with the content to be analyzed.

2. Define sets or lists of vowels and consonants.

3. Initialize counters for vowels and consonants to zero.

4. Iterate over the string, incrementing the relevant counter when a vowel or consonant is encountered.

5. Output the total counts for vowels and consonants.

3. Code Program

# Initialize the string
input_string = "Python Programming"

# Define vowels and consonants
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'

# Initialize counters
vowel_count = 0
consonant_count = 0

# Loop through the string and count vowels and consonants
for char in input_string:
    if char in vowels:
        vowel_count += 1
    elif char in consonants:
        consonant_count += 1

# Print the counts
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")


Vowels: 4
Consonants: 11


1. input_string is set to "Python Programming".

2. vowels and consonants are strings containing the respective sets of characters.

3. vowel_count and consonant_count start at 0 and will be used to keep track of the counts.

4. A for loop goes over each char in input_string.

5. The if and elif conditions use in to check membership in vowels or consonants.

6. Counts are incremented when a vowel or consonant is found.

7. After the loop, vowel_count and consonant_count contain the totals found in the string.

8. These counts are printed, showing 4 vowels and 11 consonants in the input_string.