Count Vowels in a String

This article provides a Python program to count the number of vowels in a given string. The program structure is explained in detail along with proper documentation.

Python Program

def count_vowels(input_string):
    """
    Count the number of vowels in the given string.

    Parameters:
    input_string (str): The string in which to count vowels.

    Returns:
    int: The number of vowels in the input string.
    """
    vowels = 'aeiouAEIOU'  # String containing all vowel characters
    count = 0  # Variable to store the number of vowels

    for char in input_string:  # Iterate through each character in the input string
        if char in vowels:  # Check if the character is a vowel
            count += 1  # Increment the count if it is a vowel

    return count  # Return the final count of vowels

# Example usage:
input_str = "Hello World"
print(f"The number of vowels in '{input_str}' is {count_vowels(input_str)}")

Program Explanation

The program is structured as follows:

  • def count_vowels(input_string): – This is the function definition for count_vowels which takes a single parameter, input_string.
  • vowels = 'aeiouAEIOU' – This variable contains all the vowel characters (both lowercase and uppercase).
  • count = 0 – This variable is initialized to store the count of vowels found in the input string.
  • for char in input_string: – This loop iterates through each character in the input string.
  • if char in vowels: – This conditional statement checks if the current character is a vowel.
  • count += 1 – If the character is a vowel, the count is incremented by 1.
  • return count – The function returns the total count of vowels after iterating through the input string.

Example Usage

In the example usage, the input string "Hello World" is provided to the count_vowels function. The program prints the number of vowels in the input string, which is 3 in this case.

Output:

The number of vowels in 'Hello World' is 3

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)