美文网首页
python # None

python # None

作者: FlyingPenguin | 来源:发表于2018-07-25 09:41 被阅读11次

    None
    The sole value of types.NoneType.
    None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. (python 2.7.15)
    Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.

    如果没有传递参数给函数,则默认参数为None.

    The equivalent of the null keyword in Python is None. It was designed this way for two reasons:
    Many would argue that the word "null" is somewhat esoteric.
    It's not exactly the most friendliest word to programming novices. Also, "None" refers exactly to the intended functionality - it is nothing, and has no behaviour.
    In most object-oriented languages, the naming of objects tend to use camel-case syntax. eg. ThisIsMyObject.
    As you'll see soon, Python's None type is an object, and behaves as one.

    assign the None type to a variable

    The syntax to assign the None type to a variable, is very simple. As follows:

    my_none_variable = None
    

    Checking if a Variable is None

    There are two ways to check if a variable is None. One way can be performed by using the is keyword. Another is using the == syntax. Both comparison methods are different, and you'll see why later:

    null_variable = None
    not_null_variable = 'Hello There!'
     
    # The is keyword
    if null_variable is None:
        print('null_variable is None')
    else:
        print('null_variable is not None')
     
    if not_null_variable is None:
        print('not_null_variable is None')
    else:
        print('not_null_variable is not None')
     
    
    # The == operator
    if null_variable == None:
        print('null_variable is None')
    else:
        print('null_variable is not None')
     
    if not_null_variable == None:
        print('not_null_variable is None')
    else:
        print('not_null_variable is not None')
    
    

    运行结果:

    null_variable is None
    not_null_variable is not None
    null_variable is None
    not_null_variable is not None
    

    References:

    https://docs.python.org/2/library/constants.html
    https://www.pythoncentral.io/python-null-equivalent-none/

    相关文章

      网友评论

          本文标题:python # None

          本文链接:https://www.haomeiwen.com/subject/nogumftx.html