How to Implement a Truth Table Generator in Python

A tutorial for creating truth tables for Propositional Logic in Python

Hein de Haan
Street Science

--

In this Python tutorial, you’ll learn how to build a truth table generator for Propositional Logic (PL). If you’re unfamiliar with PL, it might help to first read How To Do Propositional Logic. Furthermore, basic knowledge of the Python programming language is necessary to understand this tutorial.

A truth table of Propositional Logic combined with the Python logo.

First, let’s be clear on our goal: it is to build a Python program that receives a (compound) proposition like P ∧ Q as a string (“P ∧ Q”), and write out a truth table for that proposition.

How to write functions for the connectives of Propositional Logic

In order to create truth tables, a key ability our program needs is determining the truth value of a compound proposition. So how do we do this? Say we have P ∧ Q. Its truth value depends on the truth values of P and Q:

A truth table for the conjunction in Propositional Logic. It shows how P ∧ Q (P and Q) is only true when both P is true and Q is true, and false otherwise.
Truth table for conjunction

So a first implementation of a function to determine the truth value of a conjunction could look as follows:

--

--

Hein de Haan
Street Science

As a science communicator, I approach scientific topics using paradoxes. My journey was made possible by a generous grant from MIRI (intelligence.org).