def count_vowels(string):
"""This function counts the number of vowels (a, e, i, o, u) in a given string."""
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
return count
text = "Hello World"
print("Number of vowels:", count_vowels(text))
#source code --> clcoding.com
Code Explanation:
Function Definition
def count_vowels(string):
def is used to define the function.
count_vowels is the function name.
It takes one parameter, string (the input text).
Defining Vowels
vowels = "aeiouAEIOU"
A string containing all vowel letters (both lowercase and uppercase).
Used to check if a character is a vowel.
Initialize Vowel Count
count = 0
A variable count is set to 0 to store the number of vowels.
Loop Through the String
for char in string:
Loops through each character in the input string.
Check if Character is a Vowel
if char in vowels:
Checks if the character is present in the vowels string.
Increase the Count
count += 1
If the character is a vowel, increase the count by 1.
Return the Count
return count
The function returns the total number of vowels found in the string.
0 Comments:
Post a Comment