promotion image of download ymail app
Promoted

Python programming help?!!?

Write a program with a loop that repeatedly reads a string as input, where the string is either "duck" or "goose". The loop terminates when "goose" is entered. After the loop, your code should print out the number of "duck" strings that were read.

This has to do with sentinels and the while/for command.

2 Answers

Relevance
  • 1 month ago

    Looping on one input at a time, looking for a sentinel, is usually best done with a while loop.   The general idea is:

         <initialize>

         <get the first input>

         while <the current input is *not* the sentinel>:

              <do something with the current input>

              <get the next input>

         <terminate>

    With that type of loop, the termination condition is in the while statement at the top of the loop.  There are no break or return statements buried inside the loop body to alter the apparent logic.  It does what it says it does...loops until a sentinel is found.

    Since you have been told that every line in the input is either "duck" or "goose", and "goose" is the sentinel, then the only input lines that the <do something..> section will see are "duck" lines.  So, all that needs doing is to add to a counter.

         duck_counter += 1

    Of course, you'll need to give that a starting value before the loop; so in the <initialize> section, you can simply code:

         duck_counter = 0

    The <terminate> section is where you'll output your final count.  If the input is coming from a file rather than the console, then another <intialize> action would be to open the file; and in the <terminate> section you can close it.

    • Commenter avatarLogin to reply the answers
  • EddieJ
    Lv 7
    1 month ago

    Hi, Phillip,

    That's an imperative -- not an interrogative.

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.