温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3中怎么实现真值测试

发布时间:2021-06-17 14:58:50 来源:亿速云 阅读:234 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关python3中怎么实现真值测试,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

1. 真值测试

所谓真值测试,是指当一种类型对象出现在if或者while条件语句中时,对象值表现为True或者False。弄清楚各种情况下的真值对我们编写程序有重要的意义。

对于一个对象a,其真值定义为:

  • True : 如果函数truth_test(a)返回True。

  • False:如果函数truth_test(a)返回False。

以if为例(while是等价的,不做赘述),定义函数truth_test(x)为:

def truth_test(x):
  if x:
    return True
  else:
    return False

2.对象的真值测试

一般而言,对于一个对象,在满足以下条件之一时,真值测试为False;否则真值测试为True。

  • 其内置函数__bool__()返回False

  • 其内置函数__len__()返回0

(1)以下类型对象真值测试为真:

class X:
   pass

(2)以下真值测试为假:

class Y:
   def __bool__(self):
     return False

(3)以下真值测试为假:

class Z:
   def __len__(self):
     return 0

进入python3脚本环境,测试过程如下:

>>> class X:
...   pass
... 
>>> class Y:
...   def __bool__(self):
...     return False
... 
>>> class Z:
...   def __len__(self):
...     return 0
... 
>>> def truth_test(x):
...   if x:
...     return True
...   else:
...     return False
... 
>>> x = X()
>>> y = Y()
>>> z = Z()
>>> truth_test(x)
True
>>> truth_test(y)
False
>>> truth_test(z)
False
>>>

3. 常见对象的真值

下面是常见的真值为False的情况:

  • 常量:None and False.

  • 数值0值: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

  • 序列或者集合为空:'', (), [], {}, set(), range(0)

进入python3脚本环境,测试过程如下:

>>> truth_test(None)
False
>>> truth_test(False)
False
>>> truth_test(0)
False
>>> truth_test(0.0)
False
>>> truth_test(0j)  #复数
False
>>> truth_test(Decimal(0)) #十进制浮点数
False
>>> truth_test(Fraction(0,1)) #分数
False
>>> truth_test(Fraction(0,2)) #分数
False
>>> truth_test('')
False
>>> truth_test(())
False
>>> truth_test({})
False
>>> truth_test(set())
False
>>> truth_test(range(0)) #序列
False
>>> truth_test(range(2,2)) #序列
False

此外的其它取值,真值测试应当为True。

4.一些有意思的例子

下面是一些有意思的例子,原理不超出前面的解释。

>>> if 1 and Fraction(0,1):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and ():
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and range(0):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and None:
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1+2j and None:
...   print(True)
... else:
...   print(False)
... 
False

关于python3中怎么实现真值测试就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI