Python Program to Count the Number of Vowels in a String

Introduction

Counting the number of vowels in a string is a common task in text processing. Vowels in the English language include ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. This tutorial will guide you through creating a Python program that counts the number of vowels in a given string.

Example:

  • Input: hello world

  • Output: Number of vowels: 3

  • Input: Python Programming

  • Output: Number of vowels: 4

Problem Statement

Create a Python program that:

  • Takes a string as input.
  • Counts the number of vowels in the string.
  • Displays the total count of vowels.

Solution Steps

  1. Take Input from the User: Use the input() function to get a string from the user.
  2. Initialize a Vowel Count: Set up a counter variable to track the number of vowels.
  3. Iterate Through the String: Use a loop to iterate through each character in the string.
  4. Check for Vowels: Use a conditional statement to check if each character is a vowel.
  5. Increment the Vowel Count: Increase the counter for each vowel found.
  6. Display the Vowel Count: Use the print() function to display the total count of vowels.

Python Program

# Python Program to Count the Number of Vowels in a String # Author: https://www.rameshfadatare.com/ # Step 1: Take input from the user input_string = input("Enter a string: ") # Step 2: Initialize a vowel count vowel_count = 0 # Step 3: Define a set of vowels vowels = "aeiouAEIOU" # Step 4: Iterate through the string and count vowels for char in input_string: if char in vowels: vowel_count += 1 # Step 5: Display the vowel count print(f"Number of vowels: {vowel_count}") 

Explanation

Step 1: Take Input from the User

  • The input() function prompts the user to enter a string. The input is stored in the variable input_string.

Step 2: Initialize a Vowel Count

  • The vowel_count variable is initialized to 0 to keep track of the number of vowels found in the string.

Step 3: Define a Set of Vowels

  • A string vowels containing both lowercase and uppercase vowels is defined. This helps in checking for vowels irrespective of the case.

Step 4: Iterate Through the String and Count Vowels

  • A for loop is used to iterate through each character in the input string. If a character is found in the vowels string, the vowel_count is incremented.

Step 5: Display the Vowel Count

  • The print() function is used to display the total count of vowels in the string.

Output Example

Example 1:

Enter a string: hello world Number of vowels: 3 

Example 2:

Enter a string: Python Programming Number of vowels: 4 

Example 3:

Enter a string: Learning is Fun Number of vowels: 5 

Conclusion

This Python program demonstrates how to count the number of vowels in a string by iterating through each character and checking if it is a vowel. It’s a practical example that helps beginners understand loops, conditional statements, and string handling in Python.

Leave a Comment

Scroll to Top