Count Vowels

Count Vowels

Write a function that counts the vowels in a string.

count_vowels(text)

Count a, e, i, o, u — case-insensitive.

Examples

count_vowels("hello world")  // → 3
count_vowels("PYTHON")       // → 1
count_vowels("xyz")          // → 0
count_vowels("AEIOU")        // → 5

Walkthrough

Thinking it through

def count_vowels(text):
    count = 0
    for char in text.lower():
        if char in "aeiou":
            count += 1
    return count

Calling .lower() once on the whole string up front means the rest of the function only has to worry about lowercase vowels — much simpler than checking against both "aeiou" and "AEIOU" on every character.

char in "aeiou" uses Python's in operator for membership testing on a string — it's True exactly when char is one of those five characters, and reads almost like English. This is the same accumulator pattern as Sum To N, just counting matches instead of summing numbers: start count at 0, and add 1 every time the condition is true.

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