Python evaluates 0 as False

后端 未结 5 2101
旧时难觅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'
    
    0 讨论(0)
  • 2020-12-02 00:34

    0 is a falsy value in python

    Falsy values: from (2.7) documentation:

    zero of any numeric type, for example, 0, 0L, 0.0, 0j.

    0 讨论(0)
  • 2020-12-02 00:35

    Whatever is inside an if clause implicitly has bool called on it. So,

    if 1:
       ...
    

    is really:

    if bool(1):
       ...
    

    and bool calls __nonzero__1 which says whether the object is True or False

    Demo:

    class foo(object):
        def __init__(self,val):
            self.val = val
        def __nonzero__(self):
            print "here"
            return bool(self.val)
    
    a = foo(1)
    bool(a)  #prints "here"
    if a:    #prints "here"
        print "L"  #prints "L" since bool(1) is True.
    

    1__bool__ on python3.x

    0 讨论(0)
  • 2020-12-02 00:40

    I think it just judges by 0 or not 0:

    >>> if 0:
        print 'aa'
    
    >>> if not 0:
        print 'aa'
    
    
    aa
    >>> 
    
    0 讨论(0)
  • 2020-12-02 00:41

    In Python, bool is a subclass of int, and False has the value 0; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true.

    0 讨论(0)
提交回复
热议问题