[Tutor] Why does loop duplicate?
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Dec 16 16:50:16 EST 2015
On 16/12/2015 19:37, 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?
That's what you've told the code to do :)
>
> prefixes = 'JKLMNOPQ' ###FAILS WITH REPEATS
### OH NO IT DOESN'T - nothing personal but it's pantomine season in the
UK :)
> suffix = 'ack'
> suffixb= 'uack'
>
> for letter in prefixes:
> if letter == "O":
> print letter + suffixb
> if letter == "Q":
> print letter + suffixb
> else:
> print letter + suffix
>
You test for "O", but then follow with a test for "Q" and an else
clause. You could write :-
elif letter == "Q"
but the cleanest way of doing this is:-
for letter in prefixes:
if letter in ("O", "Q"):
print letter + suffixb
else:
print letter + suffix
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list