Count the Number of Vowels in a Given String – Python Program

 

 

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

 

Leave a Reply

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