Can anyone explain me this python code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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")

26th Sep 2018, 7:34 AM
Sarat Doni
Sarat Doni - avatar
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.
26th Sep 2018, 7:55 AM
Eduardo Petry
Eduardo Petry - avatar
+ 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.
26th Sep 2018, 7:45 AM
Eduardo Petry
Eduardo Petry - avatar
+ 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
26th Sep 2018, 8:07 AM
dhm
0
https://code.sololearn.com/c3GXx2RL4QWY/?ref=app
26th Sep 2018, 7:51 AM
Sarat Doni
Sarat Doni - avatar
0
but the output is yes .
26th Sep 2018, 7:51 AM
Sarat Doni
Sarat Doni - avatar
0
AND is higher precedence than OR in python and is evaluated first
26th Sep 2018, 8:13 AM
Sarat Doni
Sarat Doni - avatar