Python: Count String Vowels

1. Introduction

In the English alphabet, the vowels are A, E, I, O, and U (both in lowercase and uppercase). Counting the number of vowels in a string is a frequent task given in coding interviews and class exercises.

2. Program Overview

1. Prompt the user to provide a string.

2. Initialize a count for the vowels.

3. Loop through each character in the string.

4. Check if the character is a vowel.

5. If it is, increment the count.

6. After processing the entire string, print the total count of vowels.

3. Code Program

# Python program to count vowels in a string

# Taking input from the user
input_string = input("Enter a string: ").lower()

# Defining a string of vowels
vowels = 'aeiou'

# Using a list comprehension to count vowels
count = sum(1 for char in input_string if char in vowels)

print(f"Number of vowels: {count}")

Output:

Enter a string: Hello, World!
Number of vowels: 3

4. Step By Step Explanation

1. We take a string as input from the user.

2. We convert the entire string to lowercase using lower() to ensure uniformity in comparison. This way, we don't miss vowels that are in uppercase.

3. The set of English vowels (a, e, i, o, u) is defined in the variable vowels.

4. We use a list comprehension to loop through each character in the string and check if it's a vowel (i.e., if it exists in the vowels string).

5. For every vowel encountered, 1 is added to our list created through the list comprehension.

6. sum() function calculates the total number of vowels by summing up all the 1s in the list.

7. Finally, the program prints the count of vowels in the input string.

Comments