+ 2
Who can explain the following code, how this code generate 'yes' as output.
x = True y = False z = False if x or y and z: print('yes') else: print('no!')
5 odpowiedzi
+ 1
When logical OR operator is used, it checks if the first condition is true and if it evaluates to true then it leaves looking for other conditions since the first condition is true.
Variable <x> is equal to True, so it looks that the first condition is true then it leaves checking the conditions to the right side of logical OR operator.
+ 1
Pleasure.
Since <x> holds a boolean True value, the first condition is satisfied and because of the property of logical OR operator the if statement won't check other conditions and yeah logical AND operator will also not be evaluated.
+ 1
Abhishek dubey
Just thought you should know,
"and" has higher precedence over "or". So in any statement like the one in question above, "and" is always solved for first, then "or".
if True or False and False,
if True or False
if True
Hope this helps 😃😃
+ 1
Thanks Tomiwa Joseph and blACk sh4d0w for clearing this case.👍
0
Abhishek dubey I am sorry, didn't noticed about the precedence of operators. Tomiwa Joseph is correct in this case, thanks to him for identifying and correction.
Operator precedence is as follows
NOT
AND
OR
So then in this case, first logical AND is evaluated
--> False and False = False
Then logical OR operator is evaluated
--> True or False = True
So again final answer becomes True. The solution that I told you before would be correct if the expression was like this:
if (x or y) and z