Python: using exception for iteration (beginner)

I just want to know why it doesn't work (I'm trying to name the ducklings from the book: Jack, Kack, Lack, Mack, Nack, Ouack, Pack, Quack) Note: Quack and Ouack have 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
        print letter + 'u' + suffix



source to share

3 answers

This probably means:

if letter != 'O' or letter != 'Q':


The result of your original statement,

if letter != 'O' or 'Q':


compared letter

to a result 'O' or 'Q'

that is boolean (true to be exact) (so you could see why this comparison will always be true as it was).



note that

if letter != 'O' or 'Q':


in fact

if (letter != 'O') or 'Q':


This is probably not what you wanted.

Just a little test on top of it:

>>> True != False or True
>>> (True != False) or True
>>> True != (False or True)


Note. This means that the answer marked above is incorrect, the letter is not compared with the result O or Q ...



Python is not COBOL or any other language that supports this syntax. In the beginning, I would advise you to read Expressions .

Now back to your problem, what do you expect from the statement

if letter != 'O' or 'Q':



if letter != 'O' or letter != 'Q':


Interestingly, Python allows you to think laterally. For example, you can also say

letter not in ['O','Q'] 


or simply

letter not in 'OQ': #In Python Notation


or could be more expressive like

if all(letter != x for x in 'OQ'):


Just compare the above 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 even maybe

if all(letter != x for x in 'OQ'):




All Articles