+ 4

Python - How come print(1 or 0 and 0) ignores the latter 'and 0' ?

print(1 or 0 and 0) #outputs 1 1 or 0 is 1. 1 and 0 is 0. <-- Why was this latter step ignored?

4th Oct 2020, 9:49 PM
Solus
Solus - avatar
9 odpowiedzi
+ 5
Solus 1 or 0 and 0 is True. So True=1 Compare is the first -"and" , second -"or". So 0 and 0 is False (0). 1 or 0 (True or False) is True (1)
4th Oct 2020, 9:55 PM
Petr
+ 4
Mirielle[ InAcTiVe ] wow, thanks for the explanation.
5th Oct 2020, 7:10 AM
Divine Darkey
Divine Darkey - avatar
+ 3
Mirielle[ InAcTiVe ] "True which could be 1" can explain it please?
4th Oct 2020, 10:39 PM
Divine Darkey
Divine Darkey - avatar
+ 1
Python tutorial had a good table about operation precedence, is it deleted? Anyways it's all about operation precedence, operation and has higher operation precedence than operation or, and was thus evaluated first.
4th Oct 2020, 11:10 PM
Seb TheS
Seb TheS - avatar
+ 1
and groups first but isn't evaluated first. The code is interpreted this way: 1 or (0 and 0) Since 1 is truthy the second part(0 and 0) is ignored. Small test: f = lambda x: print(x) or x f(1) or f(0) and f(0)
5th Oct 2020, 12:25 AM
Kevin ★
0
OR. --compiler ignore 2nd operand if the first one is True similarly AND --compiler ignore 2nd operand if the first one is False if u not use the parantheses compiler takes everything as 2nd Operand
5th Oct 2020, 5:13 PM
Vision
Vision - avatar
0
tl:dr is a and b: If 'a' is FALSE return 'a' and skip evaluating 'b' else return 'b' a or b: If 'a' is TRUE return 'a' and skip evaluating 'b' else return 'b' Now then onto the workings of 'and' and 'or' in python. You see, in python lets say we have an expression 'a or b'. Now this expression is evaluated from LHS to RHS. An important fact bout 'or' is that if one of its args is true then the result is always true no matter the 2nd arg so assuming 'a' is true, the output will be true and there is no need to check the 2nd one cuz it doesnt matter. i.e if the 1st output is True the 2nd one is not evaluated in 'or' expressions and if the 1st is False then it will be completely dependant on the 2nd one so return 2nd one. If a is true return a else if a is false return b. So in your case '1 or 0': 1 evaluates to True so return 1. The case is similar with 'and'. Considering an expression 'a and b': return 'a' if a is false else return b cuz if one arg is false then the and evaluates to false so it will directly return a. If a is true then the output is completely dependent on b(if b is false and is false else and is true) so return b. So '1 and 0': as 1 is true return 2nd item which is 0.
6th Oct 2020, 12:00 PM
Kiran P Das
0
Хорошо учить Питона когда он на вашем родном языке. Почему нету Русского языка программирования? А то мне АНГ Плоховато поддается !))
6th Oct 2020, 12:46 PM
Разум Разумный
Разум Разумный - avatar