已解决:pyhton 中布尔值的否定

Python 中与布尔值取反相关的主要问题是它可能会造成混淆并导致意想不到的结果。 例如,如果您使用 not 运算符取反布尔值,结果可能不是您所期望的。 这是因为 Python 不会将布尔值的否定解释为它的反义词(True 变为 False,False 变为 True)。 相反,Python 将布尔值的否定解释为它的补码(True 仍然是 True,False 仍然是 False)。 当使用“and”或“or”等逻辑运算符时,这可能会导致意外结果。

#Negation of boolean in Python is done using the not operator.

boolean_value = True 
negated_boolean_value = not boolean_value 
print(negated_boolean_value) # Output: False

1. boolean_value = True:这一行将布尔值True赋值给变量boolean_value。

2. negated_boolean_value = not boolean_value:这一行使用not运算符对boolean_value的值取反,赋值给变量negated_boolean_value。

3. print(negated_boolean_value):这一行打印出negated_boolean_value的值,本例中为False。

布尔数据的否定

在 Python 中,布尔数据类型的否定是使用 not 关键字完成的。 此关键字反转布尔表达式的值,因此如果它是 True 它将变为 False,反之亦然。 例如:

x = 真
y = not x # y 现在是 False

我如何在 Python 中得到布尔值的否定

Python 中布尔值的否定可以通过使用 not 运算符来实现。 not 运算符将返回其操作数的相反布尔值。 例如,如果操作数为 True,则非运算符将返回 False。 同样,如果操作数为 False,则非运算符将返回 True。

例如:

一个 = 真
b = 不是
打印(b)#输出:假

相关文章:

发表评论