What is the value of None in memory?

前端 未结 4 423
借酒劲吻你
借酒劲吻你 2021-01-11 17:59

None in Python is a reserved word, just a question crossed my mind about the exact value of None in memory. What I\'m holding in my mind is this, <

4条回答
  •  囚心锁ツ
    2021-01-11 18:35

    None is a special constant in Python that represents the absence of a value or a null value. It is an object of its own datatype, the NoneType. We cannot create multiple None objects but can assign it to variables. These variables will be equal to one another. We must take special care that None does not imply False, 0 or any empty list, dictionary, string etc. For example:

    >>> None == 0
    False
    >>> None == []
    False
    >>> None == False
    False
    >>> x = None
    >>> y = None
    >>> x == y
    True
    

    Void functions that do not return anything will return a None object automatically. None is also returned by functions in which the program flow does not encounter a return statement. For example:

    def a_void_function():
        a = 1
        b = 2
        c = a + b
    
    x = a_void_function()
    print(x)
    

    Output: None

    This program has a function that does not return a value, although it does some operations inside. So when we print x, we get None which is returned automatically (implicitly). Similarly, here is another example:

    def improper_return_function(a):
        if (a % 2) == 0:
            return True
    
    x = improper_return_function(3)
    print(x)
    

    Output: None

    Although this function has a return statement, it is not reached in every case. The function will return True only when the input is even. So, if we give the function an odd number, None is returned implicitly.

提交回复
热议问题