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
else:
print letter + 'u' + suffix
source to share
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
>>> (True != False) or True
True
>>> True != (False or True)
False
Note. This means that the answer marked above is incorrect, the letter is not compared with the result O or Q ...
source to share
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':
definitely
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'):
source to share