Difference between “if x” and “if x is not None”

后端 未结 5 1006
萌比男神i
萌比男神i 2020-12-04 23:32

It appears that \"if x\" is almost like short-hand for the longer \"if x is not None\" syntax. Are they functionally identical or are there cases where for a given value of

5条回答
  •  萌比男神i
    2020-12-05 00:17

    if x checks if x is considered as True.

    In Python, everything has a boolean value (True/False).

    Values that are considered as False:

    • False, None
    • 0, 0.0, 0j
    • [], (), {}
    • ''
    • Other instances that signal to Python that they are empty

    Other values are considered as True. For example, [False], ('hello'), 'hello' are considered as True (because they are not empty).

    When using if x is not None, you are checking if x is not None, but it can be False or other instances that are considered as False.

    >>> x = None
    >>> if not x:print x # bool(None) is False
    None
    >>> if x == None:print x
    None
    >>> x = False
    >>> if not x:print x
    False
    >>> if x == None:print x
    

    Finally, note that True and False are respectively equal to 1 and 0:

    >>> True + 1
    2
    >>> False + 1
    1
    >>> range(1, 5)[False]
    1
    

提交回复
热议问题