This exercise combines a loop, an if, and a counter.
One new fact: a for loop works on a string. The loop variable takes each character in turn:
for letter in "hi":
print(letter)
Output:
h
i
in also checks membership in a string: "a" in "banana" is True, and "e" in "aeiou" is True.
count_vowels with one parameter, text (a lowercase string).text are vowels: a, e, i, o, or u.count_vowels("banana") returns 3.
Run your code to see the output, then press Submit.
text; for each character, check membership in "aeiou".import unittest
class TestCountVowels(unittest.TestCase):
def test_banana_has_3_vowels(self):
self.assertEqual(count_vowels("banana"), 3)
def test_rhythm_has_0_vowels(self):
self.assertEqual(count_vowels("rhythm"), 0)
def test_aeiou_has_5_vowels(self):
self.assertEqual(count_vowels("aeiou"), 5)
def test_empty_string_has_0_vowels(self):
self.assertEqual(count_vowels(""), 0)
def test_spaces_are_not_vowels(self):
self.assertEqual(count_vowels("a b c"), 1)
def count_vowels(text):
count = 0
for letter in text:
if letter in "aeiou":
count += 1
return count
print(count_vowels("banana"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.