0

Output of this confused me(I don't know diffrences between line2, 4 and 6)

print(False == False or True) print(False == (False or True)) print((False == False) or True) print(2 ** 2 == 5 or 4) print(2 ** 2 == (4 or 5)) print((2 ** 2 == 5) or 4) print((2 ** 2 == 4) or 5) print(2 + 2 == 4 or 5)

21st Jun 2020, 5:55 AM
Sasan Milan
Sasan Milan - avatar
1 Odpowiedź
+ 2
This has to do with operator precedence. I have a reference for you here: https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/precedence-associativity Basically, the logical equals operator has higher precedence than the "or" keyword, and at the same time lower precedence than the usual exponentiation or sum operators. Therefore, "False == False or True" is the same as "(False == False) or True". For "2 ** 2 == 5 or 4", an equivalent expression would be "((2 ** 2) == 5) or 4". Same with "2 + 2 == 4 or 5": "((2 + 2) == 4) or 5". You can alter the way an expression is evaluated by using explicit parentheses. Line 2: "False == (False or True)" * First, "False or True" is evaluated, which is "True". * Second, we get "False == True", which is "False". Lines 4 and 6 are equivalent to "((2 ** 2) == 5) or 4": * First, "2 ** 2" is "4". * Second, "4 == 5" evaluates to "False". * Third, "False or 4" evaluates to "4" as the "4" is a "truthy" value. (Not "True" but in a way, being an integer makes the "or" behave as an OR operation between integers; see here to check the values "True" and "False" convert to when used with integers: https://stackoverflow.com/a/2764099 )
21st Jun 2020, 5:59 AM
Felipe BF