0

I find (boolean type) and (integer) will become a integer in Python3. What conversion happens in this line of code?

flag=True
print(flag and 2)

Output:2

  • Maybe you'll find this useful. https://stackoverflow.com/questions/37888620/python-comparing-boolean-and-int-using-isinstance – rustyshackleford Jul 06 '18 at 17:09
  • if "flag" was false, output would be false... That is because the right-side part of an "and" expression is only evaluated if the left part is truthy... Try this: flag=True print(2 and flag) output: true In other words, the and operator **returns** one of the two values it operates upon. If the left side is falsy, there is no point in evaluating the right part, thus, the left part is returned. If the left part is truty, the right part is returned because there is still a chance the expression is truthy – nicolas.leblanc Jul 06 '18 at 17:14
  • `bool` has been a subclass of `int` since long before the release of Python 3 (which itself occurred nearly 10 years ago). – chepner Jul 06 '18 at 17:22

1 Answers1

1

The value of the and operator (and all other Boolean operators) will always be the last value evaluated. Operator and stops evaluation when it evaluates to False so the operand that's evaluated to False will become the value of the evaluation. Conversely, if it evaluates to True, then the operand that's evaluated to True will become the value of the evaluation.

>>> False and 2
False
>>> True and 3
3
>>> 1 and False and 3
False
>>> 1 and 0 and 3
0
Gerry L.
  • 21
  • 3
blhsing
  • 91,368
  • 6
  • 71
  • 106