Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "or" in if statement conditions [duplicate]

Tags:

python

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?

like image 782
FiveAlive Avatar asked Jan 07 '12 07:01

FiveAlive


People also ask

Can you use or in an if statement?

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)

Can IF statement have 2 conditions?

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.

Can I use if and/or together in Excel?

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.


1 Answers

Use one of the following solutions to implement the condition:

  • list: if letter in ['Q', 'O']
  • tuple: if letter in ('Q', 'O')
  • string: 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) )

like image 110
gecco Avatar answered Nov 13 '22 18:11

gecco