Practice: Count Vowels

Practice: Count Vowels

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.

Exercise

  1. Define a function named count_vowels with one parameter, text (a lowercase string).
  2. It returns how many characters of text are vowels: a, e, i, o, or u.

count_vowels("banana") returns 3.

Run your code to see the output, then press Submit.

Hints

  • Loop over text; for each character, check membership in "aeiou".
  • This is the counting accumulator from earlier in the section.

Tests

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"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.