Skip to content

Files

Latest commit

03035da · Jan 9, 2022

History

History
381 lines (249 loc) · 10.7 KB

04.md

File metadata and controls

381 lines (249 loc) · 10.7 KB

四、布尔和条件语句

布尔值是一种特定的数据类型,只能有两种可能的值之一:TrueFalse。另一种看待布尔函数的方式是考虑它的开或关。使用variable_name = boolean为变量赋值,其中boolean或者是True或者是False。不要在TrueFalse周围使用引号。请记住,引号只能用于字符串。

代码清单 97

            the_true_boolean = True
            the_other_boolean = False
            print(the_true_boolean)
            print(the_other_boolean)

输出:

代码清单 98

            True
            False

比较器

下图列出了六个运算符,它们将一个数值与另一个数值进行比较,并得出一个布尔值。

表 2:比较运算符

操作员 描述
== 等于
> 大于
>= 大于或等于
< 不到
<= 小于或等于
!= 不平等

看到1 == 2可以想“1 等于 2 吗?”如果答案是肯定的,那么就是True。如果答案是否定的,那就是False。在下面的例子中答案是否定的,所以条件将是False。注意当=给变量赋值时,==进行比较。

代码清单 99

            is_two_equal_to_three = 2 == 3
            print(is_two_equal_to_three)

输出:

代码清单 100

            False

让我们尝试在 Python 解释器中交互运行所有六个比较器中的数字12

代码清单 101

            >>> 1 == 2
            False
            >>> 1 > 2
            False
            >>> 1 >= 2
            False
            >>> 1 < 2
            True
            >>> 1 <= 2
            True
            >>> 1 != 2
            True

布尔运算符

请记住,布尔逻辑在计算机编程领域被广泛使用。布尔运算符只有三个:andornot。每一个都可以用来比较两个条件或否定一个条件。像比较器一样,它们会产生一个布尔值。

表 3:布尔逻辑运算符

操作员 描述
and 如果两个陈述都为真,则评估为True。否则评估为False
Or 如果任一陈述为真,则评估为True。否则评估为False
Not 计算结果与语句相反。

下面是一个真值表,清楚地解释了布尔运算符及其结果。

代码清单 102

            True and True is True
            True and False is False
            False and True is False
            False and False is False

            True or True is True
            True or False is True
            False or True is True
            False or False is False

            Not True is False
            Not False is True

让我们花一点时间,使用布尔and运算符评估两个语句。第一种说法是43 > 29,评估为True。第二种说法是43 < 44,也评价为True43 > 29 and 43 < 44评估为True,因为True and True评估为True

代码清单 103

            >>> 43 > 29
            True
            >>> 43 < 44
            True
            >>> 43 > 29 and 43 < 44
            True
            >>> 

43 > 29 or 43 < 44的结果是什么?

代码清单 104

          >>> 43 > 29 or 43 < 44
          True

not布尔运算符的计算结果与语句相反。既然43 > 29Truenot 43 > 29False

代码列表 105

          >>> 43 > 29
          True
          >>> not 43 > 29
          False

布尔运算符的运算顺序是:

  1. not
  2. and
  3. or

举个例子,True and False or not False就是True。首先,not False被评定为True。接下来计算True and FalseFalse。最后评估True or False,为True

代码清单 106

            >>> not False
            True
            >>> True and False
            False
            >>> True or False
            True
            >>> True and False or not False
            True

要控制操作顺序,请使用括号。任何用括号括起来的东西都将首先被求值,并作为它自己的独立单元。True and False or not False(True and False) or (not False)。也和((True and False) or (not False))一样。使用括号可以让你避免记住操作的顺序,更重要的是确保你的意图是明确和清晰的。

条件句

if语句将计算一个布尔表达式,如果是True,将执行与之相关的代码。让我们看下面的例子来看看这个演示。

代码清单 107

            if 43 < 44:
               print('Forty-three is less than forty-four.')

输出:

代码清单 108

            Forty-three is less than forty-four.

因为布尔表达式43 < 44True,所以缩进在if语句下的代码将被执行。这种缩进代码被称为代码块。右侧距离相同的任何语句也将属于该代码块。一个代码块可以包含一行或多行,它的结尾将由比当前代码块缩进少的一行来标记。另外,请记住代码块可以嵌套。下面的代码清单是代码块的逻辑视图。

代码清单 109

            Block One
               Block Two
               Block Two
                   Block Three
            Block One
            Block One

在大多数情况下,代码块使用四个空格缩进,但这更多是出于惯例,并没有严格执行。Python 将允许您在程序中使用其他级别的缩进。例如,虽然使用四个空格是缩进最流行的选择,但使用两个空格是下一个最流行的选择。然而重要的是,无论你选择哪一个,你都要坚持使用它。如果您决定使用两个空格进行缩进,那么在整个程序中继续使用两个空格。当有疑问的时候,除非你有特别的理由不这样做,否则最好遵循既定的惯例。此外,如果您遇到以下错误,这意味着您的间距有问题。

代码清单 110

            IndentationError: expected an indented block

现在让我们回到if语句。请注意,包含if语句的行总是以冒号结尾。

代码清单 111

            age = 32
            if age >= 35:
               print('You are old enough to be the President.')

            print('Have a nice day!')

输出:

代码清单 112

            Have a nice day!

在这个例子中,由于age >= 35False,缩进在if语句下面的 Python 代码没有被执行。最终的print函数将始终执行,因为它存在于if语句之外。请注意,它没有缩进。

if语句也可以与else配对。缩进在else下的代码将在if语句为假的情况下执行。试着把if/else语句理解为“如果语句是真的,运行if下面的代码”。否则运行else下面的代码。”

代码清单 113

            age = 32
            if age >= 35:
               print('You are old enough to be the President.')
            else:
               print('You are not old enough to be the President.')

            print('Have a nice day!')

输出:

代码清单 114

            You are not old enough to be the President.
            Have a nice day!

也可以使用elif来评估多个条件,T0 是“else if”的缩写例如在ifelse的情况下,您希望用冒号结束elif语句的行,并缩进要在它下面执行的代码。

代码清单 115

            age = 32
            if age >= 35:
               print('You are old enough to be a Senator or the President.')
            elif age >= 30:
               print('You are old enough to be a Senator.')
            else:
               print('You are not old enough to be a Senator or the President.')

            print('Have a nice day!')

输出:

代码清单 116

            You are old enough to be a Senator.
            Have a nice day!

在这种情况下,由于age >= 35False,所以if语句下面的代码没有被执行。由于age >= 30True,所以elif下面的代码确实执行了。else下的代码仅在前面的所有ifelif语句评估为False的情况下执行。此外,将执行第一条ifelif语句来评估True,任何剩余的elifelse块不执行。下面的清单是最后一个例子来说明前面解释的要点。

代码清单 117

            age = 103
            if age >= 35:
               print('You are old enough to be a Representative, Senator, or the President.')
            elif age >= 30:
               print('You are old enough to be a Senator.')
            elif age >= 25:
               print('You are old enough to be a Representative.')
            else:
               print('You are not old enough to be a Representative, Senator, or the President.')

            print('Have a nice day!')

输出:

代码清单 118

            You are old enough to be a Representative, Senator, or the President.
            Have a nice day!

审核

布尔人总是要么True要么False

比较器将一个数值与另一个数值进行对比,并将得出一个布尔值。

布尔运算符(andornot)比较或否定两个条件,将得到一个布尔值。

圆括号可以用来控制操作的顺序。

代码块由同一缩进级别的一段代码来标记。

条件关键字包括ifif/elseif/elif/else

练习

步行、驾驶或飞行

尝试创建一个程序,询问用户他们希望旅行多远。如果他们表达了想走不到三英里的愿望,让程序告诉他们走路。如果他们想旅行三英里以上,但不到三百英里,建议他们应该开车。在任何他们想旅行 300 英里或更多的情况下,告诉他们飞行。

样本输出:

代码清单 119

            What distance are you traveling in miles? 3125
            I suggest flying to your destination.

解决办法

代码清单 120

            # Ask for the distance.
            Distance = input(' What distance are you traveling in miles? ')

            # Convert the distance into an integer.
            Distance = int(distance)

            # Determine what transportation to use.
            if distance < 3:
               transportation = 'walking'
            elif distance < 300:
               transportation = 'driving'
            else:
               transportation = 'flying'

            # Display the result.
            Print('I suggest {} to your destination.'.format(transportation))

资源

内置类型:https://docs.python.org/3/library/stdtypes.html

操作顺序(PEMDAS):http://www.purplemath.com/modules/orderops.htm

Python 代码风格指南(PEP 8):http://legacy.python.org/dev/peps/pep-0008/