布尔表达式和决策控制

Python,如同许多其他计算机编程语言,使用布尔逻辑来进行决策控制。也就是说,Python解释器通过比较一个或多个值来决定是否执行某段代码,前提是有正确的语法和指令。

决策控制通常分为两大:条件控制和重复控制。条件逻辑使用关键字if和布尔表达式来决定是否执行代码块。重复控制则是基于条件构造,提供了一个简单的方法,在布尔表达式为真时重复执行代码块。

布尔表达式

以下是一个布尔表达式的小示例(你不必输入它):

a = 6
b = 7
c = 42
print(1, a == 6)
print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
print(8, not (a == 7 and b == 6))
print(9, not a == 7 and b == 6)

输出为:

1 True
2 False
3 True
4 False
5 True
6 True
7 False
8 True
9 False

解释一下发生了什么?该程序由一组有趣的打印语句组成。每个打印语句打印一个数字和一个布尔表达式。数字用于帮助追踪当前正在处理的语句。注意每个表达式最终都会返回TrueFalse,这些是Python内置的值。

以下是逐步解析:

  • print(1, a == 6):打印True,因为a == 6为真。

  • print(2, a == 7):打印False,因为a == 7为假。

  • print(3, a == 6 and b == 7):使用and操作符,只有两个条件都为真时,整个表达式才为真。

  • print(4, a == 7 and b == 7)and的行为:只要一个条件为假,整个表达式为假。

    and的行为总结:

    • True and True -> True
    • True and False -> False
    • False and True -> False
    • False and False -> False

    如果第一个条件为假,Python不会检查第二个条件,因为它知道整个表达式已经为假。

  • print(5, not a == 7 and b == 7)not操作符返回表达式的反值,not TrueFalsenot FalseTrue

    not的行为:

    • not True -> False
    • not False -> True
  • print(6, a == 7 or b == 7)or操作符如果第一个表达式为真,则返回True,否则检查第二个表达式。

    or的行为:

    • True or True -> True
    • True or False -> True
    • False or True -> True
    • False or False -> False
  • print(8, not (a == 7 and b == 6)):使用括号改变表达式的优先级。

  • print(9, not a == 7 and b == 6):此表达式中没有括号,因此not只作用于a == 7

示例:使用布尔表达式

list = ["Life","The Universe","Everything","Jack","Jill","Life","Jill"]

# Make a copy of the list
copy = list[:]
# Sort the copy
copy.sort()
prev = copy[0]
del copy[0]

count = 0

# Go through the list searching for a match
while count < len(copy) and copy[count] != prev:
    prev = copy[count]
    count = count + 1

# If a match was not found then count can't be < len
if count < len(copy):
    print("First Match:", prev)

输出为:

First Match: Jill

该程序通过在while count < len(copy) and copy[count] != prev条件下继续查找匹配项。当count大于copy的最后一个索引或找到匹配项时,and条件不再为真,循环退出。if语句只是检查while循环是否因为找到匹配项而退出。

and的另一个“技巧”被用在此示例中。如果你查看and的表格,会注意到第三个条目是“false and won't check”。如果count >= len(copy)(即count < len(copy)为假),那么copy[count]永远不会被查看。这是因为Python知道,如果第一个条件为假,那么两个条件都不可能为真,这就是短路(short-circuit)的概念。

示例:密码验证

# This program asks a user for a name and a password.
# It then checks them to make sure that the user is allowed in.
# Note that this is a simple and insecure example,
# real password code should never be implemented this way.

name = input("What is your name? ")
password = input("What is the password? ")
if name == "Josh" and password == "Friday":
    print("Welcome Josh")
elif name == "Fred" and password == "Rock":
    print("Welcome Fred")
else:
    print("I don't know you.")

样例运行:

What is your name? Josh
What is the password? Friday
Welcome Josh

What is your name? Bill
What is the password? Saturday
I don't know you.

练习

编写一个程序,让用户猜测你的名字,但他们只有3次机会猜测,直到程序退出。

最后修改: 2025年01月31日 星期五 00:05