This and That (or This, But Not That!)

本文详细解析了布尔运算符的优先级规则及其在编程中的应用,包括使用和注意事项,通过实例展示了如何正确地进行布尔表达式的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This and That (or This, But Not That!)

Fun fact: boolean operators can be chained together!

It's important to know that boolean operators are not evaluated straight across from left to right all the time; just like with arithmetic operators, where / and * are evaluated before + and - (remember Please Excuse My Dear Aunt Sally?), there is anorder of precedence or order of operations for boolean operators. The order is as follows:

  1. not is evaluated first;
  2. and is evaluated next;
  3. or is evaluated last.

This order can be changed by including parentheses (()). Anything in parentheses is evaluated as its own unit.

For instance, True or not False and False returns True. Can you see why? If not, check out the Hint.

Best practice: always use parentheses (()) to group your expressions to ensure they're evaluated in the order you want. Remember: explicit is better than implicit!

# Assign True or False as appropriate on the lines below!

# False or not True and True
bool_one = False or ((not True) and True)
#False

# False and not True or True
bool_two = (False and (not True)) or True
#True

# True and not (False or False)
bool_three = True and not (False or False)
#True


# not not True or False and not True
bool_four = (not (not True)) or (False and (not True))
#True

# False or not (True and True)
bool_five = False or (not (True and True))
#False

print bool_one,bool_two,bool_three,bool_four,bool_five

Go ahead and assign True or Falseas appropriate for bool_one throughbool_five. No math in this one!

Hint
  1. True or not False and False.not gets evaluated first, so we have
  2. True or True and Falseandgoes next, so we get
  3. True or False. As we've seen,True or False is True, so the value finally returned is True!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值