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?
When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False)
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
IF is one of the most popular Excel functions and very useful on its own. Combined with the logical functions such as AND, OR, and NOT, the IF function has even more value because it allows testing multiple conditions in desired combinations.
Use one of the following solutions to implement the condition:
if letter in ['Q', 'O']
if letter in ('Q', 'O')
if letter in 'QO'
Update: For completeness: Regexp: re.match('[OQ]', letter)
(copied from Paul Hankings answer (you should vote his anwer if you think regexp is THE solution) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With