3

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
1
  • 1
    What does this have to do with exceptions? Commented Mar 25, 2012 at 12:10

3 Answers 3

7

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).

Sign up to request clarification or add additional context in comments.

3 Comments

So how can I fix it to add 'u' between prefix and suffix when letter is O or Q?
@30trix: Change the or to and. Or else you can use if letter not in 'OQ':; whichever seems clearer to you, I suppose.
There are a couple of issues with this answer: 1) as pointed out by @Ondrej Kupka, the inequality comparison is evaluated first, and then the boolean one. or has a lower precedence than !=; 2) letter != 'O' or letter != 'Q' is always True. Operator precedence summary table: docs.python.org/reference/expressions.html#summary
5

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...

Comments

2

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'):

1 Comment

I slightly adjusted a couple of your examples so that they would actually work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.