I am trying to output the total of how many words start with a letter
35 words start with a letter 'a'.
wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordList = words.split()
print("Words:",len(wordList)) # prints number of words in the file.
a_words = 0
for a_words in wordList:
print(a_words, "start with the letter 'a'.")
abate start with the letter 'a'.
aberrant start with the letter 'a'.
abeyance start with the letter 'a'.
You are using the
a_words as the value of the word in each iteration and missing a counter. If we change the for loop to have
words as the value and reserved
a_words for the counter, we can increment the counter each time the criteria is passed. You could change
wordCount or something generic to make it more portable and friendly for other letters.
a_words = 0 for words in wordList: if words=='a': a_words += 1 print(a_words, "start with the letter 'a'.")