复杂的布尔表达式

  • If 语句有时候会使用更加复杂的条件布尔表达式。可能包括多个比较运算符、逻辑运算符,甚至包括算式。
if 18.5 <= weight / height**2 < 25:
      print("BMI is considered 'normal'")

  if is_raining and is_sunny:
      print("Is there a rainbow?")

  if (not unsubscribed) and (location == "USA" or location == "CAN"):
      print("send email")

注意:对于非常复杂的条件,你可能需要结合使用 and、or 和 not。使用括号可以使运算符组合更清晰。无论是简单还是复杂的条件,if 语句中的条件都必须是结果为 True 或 False 的布尔表达式,该值决定了 if 语句中的缩进代码块是否执行。

正反面示例

  • 请勿使用 TrueFalse 作为条件
# Bad example
  if True:
      print("This indented code will always get run.")

注意:虽然 True 是一个有效的布尔表达式,但不是有用的条件,因为它始终为 True,因此缩进代码将始终运行。同样,if False 也不应使用,该 if 语句之后的语句将从不运行。

# Another bad example
  if is_cold or not is_cold:
      print("This indented code will always get run.")

同样,使用你知道将始终结果为 True 的条件(例如上述示例)也是毫无用途的。布尔表达式只能为 TrueFalse,因此 is_cold 或 not is_cold 将始终为 True,缩进代码将始终运行。

  • 在使用逻辑运算符编写表达式时,要谨慎: 逻辑运算符 andornot 具有特定的含义,与字面英文意思不太一样。确保布尔表达式的结果和你预期的一样。
# Bad example
  if weather == "snow" or "rain":
      print("Wear boots!")

这段代码在 Python 中是有效的,但不是布尔表达式,虽然读起来像。原因是 or 运算符右侧的表达式 “rain” 不是布尔表达式,它是一个字符串。

  • 请勿使用 == True== False 比较布尔变量: 这种比较没必要,因为布尔变量本身是布尔表达式。
# Bad example
  if is_cold == True:
      print("The weather is cold!")

这是一个有效的条件,但是我们可以使用变量本身作为条件,使代码更容易读懂:

# Good example
  if is_cold:
      print("The weather is cold!")

备注:如果你想检查布尔表达式是否为 False,可以使用 not 运算符。

  • 在 Python 中被视为 False 的大多数内置对象
  • 定义为 false 的常量:None 和 `False
  • 任何数字类型的零:00.00jDecimal(0)Fraction(0, 1)
  • 空序列和空集合:""()[]{}set()range(0)
errors = 3
  if errors:
      print("You have {} errors to fix!".format(errors))
  else:
      print("No errors to fix!")

在上述代码中,errors 的真假值为 True,因为它是非零数字,因此输出了错误消息。