+ 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!')

29th Jul 2020, 6:27 PM
Abhishek dubey
Abhishek dubey - avatar
5 Respuestas
+ 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.
29th Jul 2020, 6:34 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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.
29th Jul 2020, 6:51 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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 😃😃
29th Jul 2020, 7:37 PM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 1
Thanks Tomiwa Joseph and blACk sh4d0w for clearing this case.👍
30th Jul 2020, 12:05 PM
Abhishek dubey
Abhishek dubey - avatar
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
30th Jul 2020, 11:41 AM
blACk sh4d0w
blACk sh4d0w - avatar