Printing the number of syllables in a word

Hello:

I’m following this exercise from a book:

Write a programme that reads a word and prints the number of syllables in the world. For this exercise, asseume that syllables are determined as follows: Each sequence of adjacent vowels a e i o u y, except for the last e in a word, is a syllable. However, if that algorithm yields a count of 0, change it to 1. For example:
Word Syllables
Harry 2
hairy 2
hare 1
the 1

In the source code for the book I have this:

##
#  Count and display the number of syllables in a word.
#

# Read input from the user.
word = input("Enter a word: ")
word = word.lower()
print(word)

# Count the syllables in the word.
syllables = 0
for i in range(len(word)) :

   # If the first letter in the word is a vowel then it is a syllable.
   if i == 0 and word[i] in "aeiouy" :
      syllables = syllables + 1

   # Else if the previous letter is not a vowel.
   elif word[i - 1] not in "aeiouy" :

      # If it is no the last letter in the word and it is a vowel.
      if i < len(word) - 1 and word[i] in "aeiouy" :
         syllables = syllables + 1

      # Else if it is the last letter and it is a vowel that is not e.
      elif i == len(word) - 1 and word[i] in "aiouy" :
         syllables = syllables + 1

# Adjust syllables from 0 to 1.
if len(word) > 0 and syllables == 0 :
   syllables == 0
   syllables = 1


# Display the result.
print("The word contains", syllables, "syllable(s)")

The comments belong to the author, not me.

I don’t get the first elif block and what this line is doing:

 elif word[i - 1] not in "aeiouy" :

Transiting the loop, word[i - 1] is the previous letter to the one picked by the loop, isn’t it?

The first if has:

if i == 0 and word[i] in "aeiouy" :

I understand that it means get the first letter in the index, and if the first letter is a vowel. But why does the author change how it refers to the first letter? It follows that this code is only applied for the first letter and only if it’s a vowel, I think.

I was testing with the word august. But I’m not sure what happens with the second letter. It seems that nothing inside the loop, as it’s not a first letter, but also doesn’t fit the elif there.

And what happens to the second U?

Also, it seems that the first elif you pick the previous letter to that one picked up in the loop?

Doing the hand tracing, I get this:

a 1 syllable
u : looks at the previous one, nothing happens.
g : looks at u, nothing happens
u: looks at the g, nothing happens
s: looks at the u adds 1 syllable.
t: nothing happens.

I didn’t find the comments very helpful here…so I thought I’ll ask here.

Thanks in advance.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.