Program to Count Vowels from a string using the Iterative method in Python
def countVowels(str): count = 0 lstVowel = ['A', 'E', 'I', 'O', 'U'] for i in range(len(str)): if str[i].upper() in lstVowel: count += 1 return count str = 'Python programming' print(countVowels(str))
Code Explanation: Count Vowels from a string using the Iterative method in Python
In this program, we have declared variable str with string value “Python programming”. And in the next line, we have called the function countVowelsinside the print statement. Count vowels accept one parameter, which is string str. Let’s check inside the function count vowels; here, we have defined variable count and initialized value 0; we will use this for the counter. In the next line, we have declared a list with all vowels with capital letters and stored them into the variable IstVowel.
In the next line, we have a for loop with counter variable i and this loop will run till the length of the string; for that, we have to use the len() function of python. Then we will check for every character from the variable str. We have if condition, and we have used counter variable i, to iterate through str and convert it into upper case and check if the character exists in the list.
If the condition is satisfied, then inside the condition, we will increment the count variable. After the loop completes, the function returns a count variable, and the system prints the count of vowels. Let’s run this program to see if we have our output, which is 4
If you want to learn python programming, you can refer to this Python Online Course with Certification. It’s easy to understand and meant for beginners who have no background in programming.