Python Program to Count Number of Vowels in a String using Sets

This Python program uses sets to count the number of vowels in a given string.

Problem Statement:

You are tasked with writing a Python program that takes a string as input and counts the number of vowels (both uppercase and lowercase) present in the string using sets.

Python Program to Count Number of Vowels in a String using Sets

def count_vowels(input_string):
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    vowel_count = 0

    for char in input_string:
        if char in vowels:
            vowel_count += 1

    return vowel_count

# Input from the user
user_input = input("Enter a string: ")
result = count_vowels(user_input)
print("Number of vowels:", result)

How it Works:

  1. The program defines a function count_vowels that takes an input string as its parameter.
  2. A set named vowels is created containing all lowercase and uppercase vowels.
  3. The program iterates through each character in the input string using a for loop.
  4. If the current character is found in the vowels set, the vowel_count is incremented by 1.
  5. After iterating through all characters, the vowel_count is returned.
  6. The user is prompted to enter a string.
  7. The count_vowels function is called with the user-input string, and the result is printed as the number of vowels in the string.

Input/Output:

Python Program to Count Number of Vowels in a String using Sets

Leave A Reply

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

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...