Reputation: 253
I have an additional question related to the link below:
Think Python (How to think like a computer scientist) - Excercise 8.4
I tried using this method to produce a solution to the ducklings problem, but it's not producing the answer I wanted. I wish to know what is wrong with my code because I can't seem to figure it out :(
as you can see, I think I set the conditions right : when the letter is O or Q, you add 'u' between the prefix and suffix, and you print everything else the way it was. But the thing is, the output is adding 'u' to everything, not just O or Q.
Is there some kind of syntax error I did wrong? I'm having a hard time trying to understand what I did wrong and I would appreciate it if anyone could point out my mistake and how to fix it. Thanks.
Upvotes: 0
Views: 170
Reputation: 11238
here, if letter =='O' or 'Q'
is read as if (letter=='O') or 'Q'
.
ie it check, that value of letter is O
or not. and using or
operations.
so when Letter=='O'
is True and Q
is always True.
so in OR
operation True&True=True
, True&False=True
, False&True=True
and False&False=False
.
so since Q
will be always True, hence the condition if letter=='O' or 'Q'
will be always true and next statement print(letter+'u'+suffix)
always executed.
to avoid this, you just also need to check if letter=='Q'
or not.This will help you to get True or False when Letter is Q
or not.
so change the code to if letter == 'O' or letter =='Q'
Upvotes: 0
Reputation: 881563
if letter == 'O' or 'Q':
does not do what you think it does (see here for operator precedence), it's equivalent to:
if (letter == 'O') or ('Q'):
And, since 'Q'
is a truthy value, the condition of that if
statement is always true. What you would need in your case would be:
if letter == 'O' or letter == 'Q':
but a more Pythonic way would be:
if letter in ['O', 'Q']:
This also better matches your original thinking where you want to detect if the letter is any of a certain group of letters, rather than explicitly checking the letter against each and every one.
Upvotes: 1