Truth Table Generator (Using Python)

binary-bannerThe 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

Before attempting this challenge, you should test your understanding of Boolean expressions, logic gates diagrams and truth tables by competing this online quiz:
Online QuizBoolean Expressions, Logic Gates Diagrams and Truth Tables

Python Bitwise Operators

To implement a Python script than can interpret a Boolean expression we will the following bitwise operators:

Bitwise Operator Example Meaning
& a & b Bitwise AND
| a | b Bitwise OR
^ a ^ b Bitwise XOR
~ ~a Bitwise NOT

Note that in Python, the following two bitwise operators can also be used to perform a bitwise left shift or right shift:

Bitwise Operator Example Meaning
<< 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

Your Task

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.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!