1

in python why

zero = 0
one = 1
if zero:
  print('True') # this print nothing
if one:
  print('True') # this print True

I thought when zero = 0, this should be the correct one. should give me True, but why nothing? If this is right, why when if one , it gives me True?

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Edward
  • 13
  • 4

3 Answers3

6

Because bool(0) == False and bool(1) == True.

Ecir Hana
  • 10,864
  • 13
  • 67
  • 117
3

Refer to this article: Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False.2.5

All other values are considered true -- so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

Shine J
  • 798
  • 1
  • 6
  • 11
1

bool is a subtype of int.

bool has two values, True and False, you can think about them as just "customized" versions of the integers 1 and 0, that only print themselves differently.

True and False behaves as 1 and 0, except that it redefines str and repr to display them differently.

>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True

>>> True == 1
True
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • It's actually not entirely relevant that `0 == False` and `1 == True`, rather, all objects are *truthy or falsey*. – juanpa.arrivillaga May 16 '20 at 06:48
  • @juanpa.arrivillaga I tried to complete the other answers. Here's a [good post](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) for an additional reference. – Maroun May 16 '20 at 06:50
  • Not sure what you meant by "subtype" but `True` and `False` are [standalone](https://github.com/python/cpython/blob/d905df766c367c350f20c46ccd99d4da19ed57d8/Include/boolobject.h#L21) objects. – Ecir Hana May 16 '20 at 06:51