Rakim24
Rakim24

Reputation: 29

'or' and 'and' in same if statement

I am wondering why this returns true:

def parrot_trouble(talking, hour):
  if hour < 7 or hour > 20 and talking == True:
    return True
  else:
    return False

print(parrot_trouble(False, 6))

Is it because you can't have 'or' and 'and' operators in same if statement? Or other reason?

Upvotes: 0

Views: 515

Answers (3)

FloLie
FloLie

Reputation: 1841

This is, because AND has priority over OR, so you have

TRUE OR (FALSE AND FALSE) resulting in TRUE

The extensive list of Operator Precedence can be found here:

Most importantly are () > not > and > or >

So to give priority to your OR operator use ()

(hour < 7 or hour > 20) and talking == True 
=> (TRUE OR FALSE) AND FALSE => FALSE

Upvotes: 4

fischmalte
fischmalte

Reputation: 81

To give some more background to the already posted answer:

This is based on operator precedence as explained here: https://docs.python.org/3/reference/expressions.html

The higher the precedence the stronger it binds its two parts. You can image that like addition and multiplication in maths. There, multiplications bind stronger. Here, the and binds stronger as written in a different answer.

Upvotes: 2

Klein -_0
Klein -_0

Reputation: 158

It's about the operator's precedence enter image description here In order to make that work you will need to specify the order of operators with parantheses.

def parrot_trouble(talking, hour):
  if (hour < 7 or hour > 20) and talking == True:
    return True
  else:
    return False

print(parrot_trouble(False, 6))

What is in parantheses will be executed first and then compared to and.

Upvotes: 1

Related Questions