Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 1
Can anyone explain me this python code
x = True y = False z = False if x or y and z: print("yes") else: print("no")
6 Answers
+ 8
Interesting. So what's happening is that the expression is being evaluated as x or (y and z) == True.
If you want it to get evaluated to False, you should specify the order of precedence as (x or y) and z.
+ 4
The "or" operation evaluates to True if either operands are True.
True or False == True
The "and" operation evaluates to True only if both operands are True.
True and False == False
Therefore, x or y and z evaluates to False, which makes the else statement be executed.
+ 1
It's good practice to use parenthesis to define the order of your logical operations.
Furthermore, if you are not sure of what to expect with a complex logical expression, try to imagine the different cases given the inputs or even write it down and go as far as making a truth table if needed.
Some things become intuitive only after a while.
EDIT : if you're interested in operator precedence in python, you can find it here :
https://docs.python.org/3/reference/expressions.html#operator-precedence
0
https://code.sololearn.com/c3GXx2RL4QWY/?ref=app
0
but the output is yes .
0
AND is higher precedence than OR in python and is evaluated first