布尔与、布尔或、布尔非不仅能对布尔值进行运算,还可以对其他类型进行运算。布尔与为x and y,如果x为True则返回y值,如果x为False则返回x值。布尔或为x or y,如果x为True则返回x值,如果x为False则返回y值。
在了解了逻辑运算符之后编写实例进行验证,在basis目录下新建文件,命名为logic.py,学习Python逻辑运算符的操作,在PyCharm中输入代码。
operand_a = 5
operand_b = 2
operand_c = 0
operand_d = 0
布尔与
operand_d = operand_a and operand_b
print("{} and {} = {}".format(operand_a, operand_b, operand_d))
operand_d = operand_a and operand_c
print("{} and {} = {}".format(operand_a, operand_c, operand_d))
operand_d = operand_c and operand_a
print("{} and {} = {}".format(operand_c, operand_a, operand_d))
operand_d = operand_c and operand_c
print("{} and {} = {}".format(operand_c, operand_c, operand_d))
布尔或
operand_d = operand_a or operand_b
print("{} or {} = {}".format(operand_a, operand_b, operand_d))
operand_d = operand_a or operand_c
print("{} or {} = {}".format(operand_a, operand_c, operand_d))
operand_d = operand_c or operand_a
print("{} or {} = {}".format(operand_c, operand_a, operand_d))
operand_d = operand_c or operand_c
print("{} or {} = {}".format(operand_c, operand_c, operand_d))
布尔非
operand_d = not operand_a
print("not {} = {}".format(operand_a, operand_d))
operand_d = not operand_c
print("not {} = {}".format(operand_c, operand_d))