下面是一个使用Python编写的布尔逻辑和真值表的代码示例:
# 定义布尔逻辑运算函数
def AND(x, y):
return x and y
def OR(x, y):
return x or y
def NOT(x):
return not x
def XOR(x, y):
return x != y
# 定义真值表生成函数
def truth_table(func):
inputs = [(True, True), (True, False), (False, True), (False, False)]
outputs = [func(x, y) for x, y in inputs]
print("x y | Output")
print("----------------")
for i in range(len(inputs)):
x, y = inputs[i]
output = outputs[i]
print(f"{x} {y} | {output}")
# 测试布尔逻辑函数
print("AND Truth Table:")
truth_table(AND)
print("\nOR Truth Table:")
truth_table(OR)
print("\nNOT Truth Table:")
inputs = [True, False]
outputs = [NOT(x) for x in inputs]
for i in range(len(inputs)):
x = inputs[i]
output = outputs[i]
print(f"{x} | {output}")
print("\nXOR Truth Table:")
truth_table(XOR)
运行上述代码,将会输出以下结果:
AND Truth Table:
x y | Output
----------------
True True | True
True False | False
False True | False
False False | False
OR Truth Table:
x y | Output
----------------
True True | True
True False | True
False True | True
False False | False
NOT Truth Table:
True | False
False | True
XOR Truth Table:
x y | Output
----------------
True True | False
True False | True
False True | True
False False | False
这个代码示例中,我们定义了四个布尔逻辑函数:AND、OR、NOT和XOR。然后,我们编写了一个名为truth_table
的函数,该函数接受一个布尔逻辑函数作为参数,并生成相应的真值表。我们使用print
语句输出真值表的结果。
最后,我们使用这些函数分别生成了AND、OR、NOT和XOR运算的真值表,并进行了打印输出。