Reputation: 2016
I just want to know why this doesn't work (I am trying to name the ducklings from a book: Jack, Kack, Lack, Mack, Nack, Ouack, Pack, Quack) Note: Quack and Ouack have a U
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
if letter != 'O' or 'Q': #I know this doesn't work, need to know alternative
print letter + suffix
else:
print letter + 'u' + suffix
Upvotes: 3
Views: 188
Reputation: 63737
Python is not COBOL or some other language which supports this syntax. As a start I would suggest you read Expressions.
Now coming back to your problem, what you expect from the statement
if letter != 'O' or 'Q':
definitely
if letter != 'O' or letter != 'Q':
interestingly Python allows you to think laterally. For example you might also say,
letter not in ['O','Q']
or simply
letter not in 'OQ': #In Python Notation
or can be more expressive like
if all(letter != x for x in 'OQ'):
Just compare the above mentioned syntax and usage with yours
When you wrote
if letter != 'O' or 'Q':
which in Python should be written as
if letter not in 'OQ':
or may even be
if all(letter != x for x in 'OQ'):
Upvotes: 2
Reputation: 1057
Please note that
if letter != 'O' or 'Q':
is in fact
if (letter != 'O') or 'Q':
That is probably not what you wanted.
Just a small test on top of it:
>>> True != False or True
True
>>> (True != False) or True
True
>>> True != (False or True)
False
Note: This means that the answer marked on top is not true, letter is not compared to the result of O or Q...
Upvotes: 5
Reputation: 76955
You likely mean this:
if letter != 'O' or letter != 'Q':
The result of your original statement,
if letter != 'O' or 'Q':
compared letter
to the result of 'O' or 'Q'
, which is a boolean (true to be exact) (so you could see why this comparison would always be true as it was).
Upvotes: 7