+ 1
x = True;?
x = True; y = False; z = False; if (not x or y): print("1") elif(not x or not y and z): print("2") elif(not x or y or not y and x): print("3") else: print("4") OUTPUT: 3 #Let's evaluate True to 1 and false to 0. So if not 1 or 0 print 1 (cannot be so as could be "or"), If not 1 or not 0 and 0 print 2 (nothing is disqualified, so I guess this is a no). elif not 1 or 0 or not 0 and 1 print three (This comes up as the correct answer but completely confused about why? Is it because one "or" zero vs. not zero "and" one? Any ideas? Thanks to all.
3 Respostas
+ 3
Let's get something clear first.
True = 1, False = 0.
not True = False,
not False = True.
"and" => evaluates to true ONLY IF BOTH operand are True.
"or" => evaluates to True if AT LEAST 1 of the operands is true .
Now, Looking at statement 3
===≠====≠======≠=====
elif((not x or y) or (not y and x))
I've put parentheses to make it clearer.
Now let's evaluate each parentheses one by one.
First:: (not x or y) = (False or False )
which results in False since none of the operand is True.
Second:: (not y and x) = (True and True)
Which results in True since at least one of the operand is True..
Back to the main parentheses
elif((not x or y) or (not y and x)) => (False or True )
Which results in True, therefore 3 is printed
+ 1
Adding to D'Lite's answer, the "and" operator has higher precedence than the "or" operator.
0
Thanks DL and Diego👍🏻