Fall 2024 - P3
3.5 Booleans; Truth Table (Period 3)
Student led teaching on Booleans. Learn how booleans are used in decision-making with logical operators.
Python Truth Table
What is a Truth Table?
A truth table is a table that displays the logical operations on input signals in a table format.
- Remember
||
means OR.
import itertools
# Define the variables (A, B, C), 3 in this case
variables = ['A', 'B']
# Use itertools.product to generate the truth table
truth_table_itertools = list(itertools.product([False, True], repeat=len(variables)))
# Print the truth table
print("| A | B | A AND B | A OR B |")
print("----------------------------------------")
for table in truth_table_itertools:
print("| "+ str(table[0]) + " | " + str(table[1]) + " | " + str(table[0] and table[1]) + " |" + str(table[0] or table[1]) + " |")
| A | B | A AND B | A OR B |
----------------------------------------
| False | False | False |False |
| False | True | False |True |
| True | False | False |True |
| True | True | True |True |