zoukankan      html  css  js  c++  java
  • Python基础学习之布尔表达式

    在Python编程的学习中,布尔逻辑可以说是无处不在。布尔表达式是计算机运算的基础和重要组成部分,掌握它们就跟学音乐要掌握音阶一样有必要。今天本文将带大家一起来学习布尔表达式,主要内容有布尔表达式的概念、逻辑问题演示以及理清复杂逻辑的技巧。


     

    1、布尔表达式的概念

    条件语句和循环语句都使用布尔表达式作为条件。布尔值为真或假,以False和True表示,前面经常使用布尔表达式比较两个值,如: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基础学习的过程中,布尔表达式可能会让初学者感觉到复杂和困难。但是只要通过更多的相关练习,相信大家可以很快理解布尔表达式并熟练运用它。即便是现在暂时的不理解也没关系,只要你坚持下去了,量变终会影响质变!

  • 相关阅读:
    CADisplayLink
    对项目重命名
    TCP|UDP|Http|Socket
    CoreAnimation|动画
    Autolayout
    通讯录
    本地通知
    用于做 Android 屏幕自适应的文章资源
    Java String.format 自动补全不够的位数
    不同语言之间 日期格式转换
  • 原文地址:https://www.cnblogs.com/nanhe/p/13498924.html
Copyright © 2011-2022 走看看