温馨提示×

温馨提示×

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

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

Python中布尔表达式怎么用

发布时间:2021-10-27 17:31:33 来源:亿速云 阅读:281 作者:小新 栏目:编程语言

小编给大家分享一下Python中布尔表达式怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

1、布尔表达式的概念

条件语句和循环语句都使用布尔表达式作为条件。布尔值为真或假,以FalseTrue表示,前面经常使用布尔表达式比较两个值,如:while x>=0 

2、逻辑问题演示

True and True

False and True

1 == 1 and 2 == 1

"test" == "test"

1 == 1 or 2 != 1

True and 1 == 1

False and 0 != 0

True or 1 == 1

"test" == "testing"

1 != 0 and 2 == 1

"test" != "testing"

"test" == 1

not (True and False)

not (1 == 1 and 0 != 1)

not (10 == 1 or 1000 == 1000)

not (1 != 10 or 3 == 4)

not ("testing" == "testing" and "Zed" == "Cool Guy")

1 == 1 and (not ("testing" == 1 or 1 == 0))

"chunky" == "bacon" and (not (3 == 4 or 3 == 3))

3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))

所有的布尔逻辑表达式都可以用下面的简单流程得到结果:

1)找到相等判断的部分 ( == 或者 != ),将其改写为其最终值 ( True False )

2)找到括号里的 and/or ,先算出它们的值。

3)找到每一个 not ,算出他们反过来的值。

4)找到剩下的 and/or ,解出它们的值。

5)等你都做完后,剩下的结果应该就是 True 或者 False 了。

下面我们以20行的逻辑表达式演示一下:

3 != 4 and not ("testing" != "test" or "Python" == "Python")

接下来你将看到这个复杂表达式是如何逐级解为一个单独结果的:

1. > 解出每一个等值判断:

> a. 3 != 4 True : True and not ("testing" != "test" or "Python" == "Python") b.

"testing" != "test" True : True and not (True or "Python" == "Python") c.

"Python" == "Python" True : True and not (True or True)

1. > 找到括号中的每一个 and/or :

> a. (True or True) True: True and not (True)

1. 找到每一个 not 并将其逆转:> > a. not (True) False: True and False

1. 找到剩下的 and/or ,解出它们的值:> > a. True and False False

这样我们就解出了它最终的值为 False.

3、理清复杂逻辑的技巧

这里告诉大家一条捷径去判断布尔表达式的值。任何的 and 表达式包含一个 False 结果就是 False ,任何 or 表达式有一个 True 结果就是 True ,你就可以在此处得到结果,但要确保你能处理整个表达式,因为后面这是一个很有用的技能。

以上是“Python中布尔表达式怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

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

AI