def count_vowels(input_string):
vowels = {'a', 'e', 'i', 'o', 'u'}
input_string = input_string.lower()
vowel_count = sum(1 for char in input_string if char in vowels)
return vowel_count
input_string = input("Enter a string: ")
print(f"Number of vowels: {count_vowels(input_string)}")
#source code --> clcoding.com
Code Explanation:
Defining the Function:
def count_vowels(input_string):
This defines a function called count_vowels that takes one argument, input_string. This argument will hold the string in which vowels will be counted.
2. Defining the Set of Vowels:
vowels = {'a', 'e', 'i', 'o', 'u'}
A set named vowels is defined containing all lowercase vowels (a, e, i, o, u).
Sets are used here because they allow efficient membership checks (char in vowels).
3. Converting the Input String to Lowercase:
input_string = input_string.lower()
The input_string is converted to lowercase using the .lower() method to handle both uppercase and lowercase vowels uniformly. For example, "A" will be treated as "a".
4. Counting the Vowels:
vowel_count = sum(1 for char in input_string if char in vowels)
A generator expression is used to iterate through each character in the input_string.
For each character, it checks if the character exists in the vowels set.
If the character is a vowel, 1 is added to the sum.
The sum function computes the total count of vowels in the string.
5. Returning the Count:
return vowel_count
The function returns the total number of vowels found in the input string.
6. Getting User Input and Printing the Result:
input_string = input("Enter a string: ")
print(f"Number of vowels: {count_vowels(input_string)}")
The user is prompted to enter a string using the input() function.
The entered string is passed as an argument to the count_vowels function.
The result (number of vowels) is printed to the console using an f-string for formatting.
0 Comments:
Post a Comment