Here’s a Python program that counts the number of each vowel in a string:
Approach 1:
# Python program to count the number of each vowel in a string # input string string = input("Enter a string: ") # initialize count variables a_count = 0 e_count = 0 i_count = 0 o_count = 0 u_count = 0 # iterate through each character in the string for char in string: if char.lower() == 'a': a_count += 1 elif char.lower() == 'e': e_count += 1 elif char.lower() == 'i': i_count += 1 elif char.lower() == 'o': o_count += 1 elif char.lower() == 'u': u_count += 1 # print the counts print("Number of 'a' in the string: ", a_count) print("Number of 'e' in the string: ", e_count) print("Number of 'i' in the string: ", i_count) print("Number of 'o' in the string: ", o_count) print("Number of 'u' in the string: ", u_count)
In this program, we first ask the user to input a string. Then we initialize count variables for each vowel to 0. We then iterate through each character in the string using a for loop, and for each character, we check if it is a vowel (both uppercase and lowercase). If it is a vowel, we increment the corresponding count variable. Finally, we print the counts for each vowel.
Approach 2: Program to count the number of each vowel in a string Using function.
# Function to count the number of each vowel in a string def count_vowels(string): # initialize count variables a_count = 0 e_count = 0 i_count = 0 o_count = 0 u_count = 0 # iterate through each character in the string for char in string: if char.lower() == 'a': a_count += 1 elif char.lower() == 'e': e_count += 1 elif char.lower() == 'i': i_count += 1 elif char.lower() == 'o': o_count += 1 elif char.lower() == 'u': u_count += 1 # return the counts as a dictionary return {'a': a_count, 'e': e_count, 'i': i_count, 'o': o_count, 'u': u_count} # input string string = input("Enter a string: ") # call the function and print the results vowel_counts = count_vowels(string) print("Number of 'a' in the string: ", vowel_counts['a']) print("Number of 'e' in the string: ", vowel_counts['e']) print("Number of 'i' in the string: ", vowel_counts['i']) print("Number of 'o' in the string: ", vowel_counts['o']) print("Number of 'u' in the string: ", vowel_counts['u'])
In this program, we define a function called count_vowels
that takes a string as input and returns a dictionary containing the counts of each vowel in the string. The implementation of the function is similar to the previous program, except that instead of printing the counts, we return them as a dictionary.
We then ask the user to input a string and call the count_vowels
function with the string as input. We store the returned dictionary in a variable called vowel_counts
. Finally, we print the counts for each vowel by accessing the corresponding values in the vowel_counts
dictionary.