[Tutor] Why does loop duplicate?

Steven D'Aprano steve at pearwood.info
Wed Dec 16 17:58:21 EST 2015


On Wed, Dec 16, 2015 at 02:37:18PM -0500, Ken Hammer wrote:

> Intent is to print "Jack, Kack, ...." with "O" and "Q" delivering a 
> longer suffix.  Instead, I get the printout shown with duplicates and 
> a second deviation with "O" and "Q" as shown. Why?

Are you absolutely sure about that? When I run your code, I don't get 
any duplicates:


prefixes = 'JKLMNOPQ'   ###FAILS WITH REPEATS
suffix = 'ack'
suffixb= 'uack'
 
for letter in prefixes:
    if letter == "O":
        print letter + suffixb
    if letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix

Output is:

Jack
Kack
Lack
Mack
Nack
Ouack
Oack
Pack
Quack


If you are getting duplicate lines, you must be running code that is 
different from the code you posted to us. We cannot help you with code 
we can't see.

As far as the code shown, look carefully at the code inside the 
for-loop:

    if letter == "O":
        print letter + suffixb
    if letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix


The first test checks to see if the letter is "O", and if so, it prints 
"Ouack". Then, *regardless* of whether it just printed "Ouack" or not, 
it then does a second test, for "Q". Since Q is not O, it then prints 
"Oack".

No other letter gets treated that way.

Instead, you should change the second "if" to an "elif" (else if). Or 
better still:

    if letter == "O" or letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix


which can be simplified even more to:

    if letter in ("O", "Q"):
        print letter + suffixb
    else:
        print letter + suffix



-- 
Steve


More information about the Tutor mailing list