zoukankan      html  css  js  c++  java
  • Python中对变量是否为None的判断

    三种主要的写法有:

    第一种:if X is None;

    第二种:if not X;

    当X为None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()这些时,not X为真,即无法分辨出他们之间的不同。

    第三种:if not X is None;

     在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。

    在命令if not 1中,1便会转换为bool类型的True。not是逻辑运算符非,not 1则恒为False。因此if语句if not 1之下的语句,永远不会执行。

    ========================================================================================

    对比:foo is None 和 foo == None

    示例:

    >>> class Foo(object):
           def __eq__(self, other):
               return True
    
    >>> f = Foo()
    >>> f == None
    True
    >>> f is None
    False

    =============================================

    python中的not具体表示是什么,举个例子说一下,衷心的感谢

    在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法:
    (1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。比如:
    a = False
    if not a:   (这里因为a是False,所以not a就是True)
        print "hello"
    这里就能够输出结果hello
    (2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,比如:
    a = 5
    b = [1, 2, 3]
    if a not in b:
        print "hello"
    这里也能够输出结果hello
    not x     意思相当于     if x is false, then True, else False

    =====================================================================================================

    感谢

    参考来源:http://blog.csdn.net/sasoritattoo/article/details/12451359

    http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none

    http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none

  • 相关阅读:
    51nod 1087 1 10 100 1000(找规律+递推+stl)
    51nod 1082 与7无关的数 (打表预处理)
    51 nod 1080 两个数的平方和
    1015 水仙花数(水题)
    51 nod 1003 阶乘后面0的数量
    51nod 1002 数塔取数问题
    51 nod 1001 数组中和等于K的数对
    51 nod 1081 子段求和
    51nod 1134 最长递增子序列 (O(nlogn)算法)
    51nod 1174 区间中最大的数(RMQ)
  • 原文地址:https://www.cnblogs.com/wangzhao2016/p/6763431.html
Copyright © 2011-2022 走看看