0

Hello I need help counting the number of words that begin with the letter 'a' where we store in num_with_a and 'd' where we store in num_with_d from a given book_excerpt.

book_excerpt = "It was both the greatest and worst of times; it was the Age of Wisdom and the Age of Folly; it was the Epoch of Belief and the Epoch of Skepticism; it was the Age of Light and the Age of Darkness; it was the Spring of Hope and the Winter of Despair."

This is what I tried:

num_with_a = for f in book_excerpt:
   
    if beginning 'a' in f:

      print(f)

num_with_d = for f in book_excerpt:
    
    if beginning 'd' in f:
       
      print(f)
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
anj_M1
  • 19
  • 2
  • 2
    Okay... What happened? Presumably you got a `SyntaxError`? (Also have you tried any Python introductory tutorials yet, such as [the official one](https://docs.python.org/3/tutorial/)? They can help show you the basics of how `for` loops work.) Welcome to Stack Overflow, by the way. Good places to check out first are the [tour], [ask], and [MRE]. – CrazyChucky Feb 21 '23 at 02:28

1 Answers1

-1

You can use a for loop:

book_excerpt = "It was both the greatest and worst of times; it was the Age of Wisdom and the Age of Folly; it was the Epoch of Belief and the Epoch of Skepticism; it was the Age of Light and the Age of Darkness; it was the Spring of Hope and the Winter of Despair."

words = book_excerpt.split(" ")
count = 0
for i in words:
    if list(i)[0].lower() == "a":
        count += 1
print(count)

Output:

9

How this works:

Gets every word with book_excerpt.split(" "). Then loops through the words with the for loop. If a word's first index (word is changed into a list) is the letter, then it adds to the count.

What's wrong with your code

  1. You can't set a variable to the value of a for loop

(I'm referring to this line) num_with_a = for f in book_excerpt:

  1. You need to turn book_excerpt into a list before looping through it. The best way to do this would be to split it by words.
Blue Robin
  • 847
  • 2
  • 11
  • 31