Python evaluates 0 as False

后端 未结 5 2126
旧时难觅i
旧时难觅i 2020-12-01 23:52

In the Python console:

>>> a = 0
>>> if a:
...   print \"L\"
... 
>>> a = 1
>>> if a:
...   print \"L\"
... 
L
>>&g         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-02 00:15

    First of all, everything in python is an object. Therefore, your 0 is also an object, specifically, a built-in object.

    Here are the built-in objects considered as false:

    1. constants defined to be false: None and False.
    2. zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
    3. empty sequences and collections: '', (), [], {}, set(), range(0)

    So when you put 0 in an if or while condition, or in a Boolean operation, it is tested for truth value.

    # call the __bool__ method of 0
    >>> print((0).__bool__())
    False
    
    # 
    >>> if not 0:
    ...     print('if not 0 is evaluated as True')
    'if not 0 is evaluated as True'
    

提交回复
热议问题