2

Below is the scenario.

>>> False and 0
=> False
>>> 0 and False
=> 0

Both the conditions are same, but why is it returning different results?

>>> 0 or False
=> False
>>> False or 0
=> 0

Similarly, both the conditions should return same results, but why are they different?

The same applies in case of True and 1

radh
  • 179
  • 1
  • 1
  • 7

3 Answers3

1

In python, theand, or operators do not return boolean. They return the last thing evaluated. Since they are short circuit operators, the last thing that need to be evaluated for the expression 0 and False, is0. Similarly, for 0 or False, the last thing that needs to be checked is the second operand, False.

From the python documentation:

  • x or y: if x is false, then y, else x
  • x and y: if x is false, then x, else y
  • not x: if x is false, then True, else False
blue_note
  • 27,712
  • 9
  • 72
  • 90
0

Python conditional checking uses Short-Circuit Evaluation. This means the following:

False and 0

It is executing an and statement, so both elements must evaluate to 1. Since False doesn't, it does not check for the second one and it returns False. This also applies for 0 and False, but since 0 is the first element it returns 0.

False or 0

In this case it is performing an or evaluation so one of the elements must evaluate to 1 (or True). Since False doesn't, it checks for the second operator (0) which neither evaluates to 1, so it returns it. The same applies for 0 or False.

Here you have another approach that clears out any doubt. Using 0 or "Text" it returns "Text" as it evaluates to True.

Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
0

or is a short-circuit operator, so it only evaluates the second argument if the first one is false. In the case, False or 0, first argument is evaluated to False, then second argument is evaluated, which is 0, and returns 0. This is valid for both the cases(0 or False too).

and is also a short-circuit operator, so it only evaluates the second argument if the first one is true. In the case False and 0, the first argument is evaluated to False, then the second is not evaluated and returns the first argument and vice versa.

For more clarification, refer the docs.

zaidfazil
  • 9,017
  • 2
  • 24
  • 47