Skip to content
Advertisement

Syllable Count In Python

I need to write a function that will read syllables in a word (for example, HAIRY is 2 syllables). I have my code shown on the bottom and I’m confident it works in most cases, because it works with every other test I’ve done, but not with “HAIRY” where it only reads as 1 syllable.

def syllable_count(word):
    count = 0
    vowels = "aeiouy"
    if word[0] in vowels:
        count += 1
    for index in range(1, len(word)):
        if word[index] in vowels and word[index - 1] not in vowels:
            count += 1
            if word.endswith("e"):
                count -= 1
    if count == 0:
        count += 1
    return count

TEST

print(syllable_count("HAIRY"))

Expected: 2

Received: 1

Advertisement

Answer

The problem is that you’re giving it an uppercase string, but you only compare to lowercase values. This can be fixed by adding word = word.lower() to the start of your function.

def syllable_count(word):
    word = word.lower()
    count = 0
    vowels = "aeiouy"
    if word[0] in vowels:
        count += 1
    for index in range(1, len(word)):
        if word[index] in vowels and word[index - 1] not in vowels:
            count += 1
    if word.endswith("e"):
        count -= 1
    if count == 0:
        count += 1
    return count

print(syllable_count('HAIRY'))  # prints "2"
Advertisement