DEV Community

Emmanuel Adetoro
Emmanuel Adetoro

Posted on

Counting Vowels in a String: A Simple Python Program Tutorial

Introduction

This program counts the number of vowels in a given string. It is a simple yet useful program that can be used to analyze text data and extract information about the vowels in a sentence, word or paragraph.

Prerequisites

To follow this tutorial, you should have a basic understanding of Python programming and be familiar with string manipulation and control structures.

Steps

First, we need to prompt the user to enter the string to be analyzed. We can use the input() function to ask the user for a string input and store it in a variable.

string = input("Please enter a string to count the vowels: ")
Enter fullscreen mode Exit fullscreen mode

Next, we need to initialize a count variable to keep track of the number of vowels in the string. We can use a for loop to iterate through each character in the string and check if it is a vowel.

vowels = "aeiouAEIOU"
count = 0
for char in string:
    if char in vowels:
        count += 1
Enter fullscreen mode Exit fullscreen mode

Here, we define a string of vowels and initialize the count variable to zero. We then loop through each character in the input string and check if it is a vowel. If the character is a vowel, we increment the count variable by 1.

Finally, we can print the number of vowels in the string to the console.

print(f"There are {count} vowels in the string '{string}'.")
Enter fullscreen mode Exit fullscreen mode

Here, we use string formatting to print a message to the console that displays the number of vowels in the input string.

Full code

Here's the full code for the program:

string = input("Please enter a string to count the vowels: ")
vowels = "aeiouAEIOU"
count = 0
for char in string:
    if char in vowels:
        count += 1
print(f"There are {count} vowels in the string '{string}'.")
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we learned how to create a program that takes a string as input and counts the number of vowels in it. We used a for loop to iterate through each character in the string and checked if it was a vowel. We then printed the count of vowels in the string to the console. This program can be a useful tool for analyzing text data and extracting information about vowels in sentences, words or paragraphs.

Top comments (0)