I’m sure there is a really simple answer to this but I can’t find it after searching around for a while.
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
if letter == "Q" or letter == "O":
print letter + "u" + suffix
else:
print letter + suffix
The above code works perfectly, the condition on the if statement seems a bit long-winded so I tried:
if letter == "Q" or "O":
which is shorter but doesn’t work. I worked out that it doesn’t work because “O” is a boolean expression which will always be True and that it doesn’t consider anything on the left side of “or”.
I tried putting brackets around it like so:
if letter == ("Q" or "O"):
but that only matches Q and not O.
Is there any shorthand way of getting the code to work or do I have to use the long-winded way that’s working for me?
You can use
letter in 'OQ'orre.match('[OQ]', letter)More thoroughly, I’d probably define a string of prefixes that should get the ‘u’.
In your code,
letter == ("O" or "Q")first evaluates("O" or "Q")(“O” isn’t false, so the result is “O”) and so this is the same asletter == "O".Your other attempt,
letter == "O" or "Q"first evaluatesletter == "O"and if it’s True, it gives the answer True otherwise it’ll give the answer “Q”.You can find the documentation for how
orworks in the language reference.