Learn Programming and technology with ease @ developerpublish.com

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

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:

You May Also Like

Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...