Welcome to our lesson on counting vowels and consonants in a string! This skill is essential in many programming tasks, such as text analysis, spell checking, and natural language processing. Let's get started! šÆ
In English, vowels are the letters a, e, i, o, and u, while consonants are all other alphabets. Vowels can make sounds on their own, while consonants cannot. Let's move on! šÆ
In Python, a string is a sequence of characters. Strings are enclosed in single or double quotes. For example:
my_string = "Hello, World!"To iterate through each character in a string, we use a loop. Here's an example using a for loop:
my_string = "Hello, World!"
for char in my_string:
print(char)To determine whether a character is a vowel or a consonant, we can use a simple conditional statement. In Python, we'll define a list of vowels and compare each character against this list:
vowels = ["a", "e", "i", "o", "u"]Now that we can check if a character is a vowel or a consonant, we can count them in a string. We'll use two variables, vowel_count and consonant_count, to keep track of the counts:
my_string = "Hello, World!"
vowel_count = 0
consonant_count = 0
for char in my_string:
if char.lower() in vowels:
vowel_count += 1
elif char.isalpha():
consonant_count += 1Let's count the vowels and consonants in a sentence:
sentence = "The quick brown fox jumps over the lazy dog."
vowel_count = 0
consonant_count = 0
for char in sentence:
if char.lower() in vowels:
vowel_count += 1
elif char.isalpha():
consonant_count += 1
print("Vowels:", vowel_count)
print("Consonants:", consonant_count)Which of the following is a vowel in English?
What is the purpose of the `vowels` list in our code?
Keep learning and coding! š