The purpose of this blog post is to write a Python script that will interpret a Boolean expression and output its full Truth Table.
Boolean Expressions & Truth Tables
Python Bitwise Operators
To implement a Python script than can interpret a Boolean expression we will the following bitwise operators:
|&||a & b||Bitwise AND|
||||a | b||Bitwise OR|
|^||a ^ b||Bitwise XOR|
Note that in Python, the following two bitwise operators can also be used to perform a bitwise left shift or right shift:
|<<||a << n||Bitwise left shift by n places|
|>>||a >> n||Bitwise right shift by n places|
Python Code (Solution)
Here is the Python code for our Truth Table Generator function truthTable() which takes two parameters:
- A Boolean expression: e.g. A AND NOT (B OR C)
- The number of inputs: either 2, 3 or 4: A, B, C and D
Write an additional function to perform a bitwise left shift or a bitwise right shift using the bitwise operators << and >>.
Check that performing a left shift by n place(s) is equivalent to multiplying a number by 2n.
For instance 5 << 3 is the same as 5×23 = 40.
Check that performing a right shift by n place(s) is equivalent to dividing a number by 2n (whole division).
For instance 40 >> 3 is the same as 40/23 = 5.