Andrew J. answered 07/11/19
Professional Software Developer with Python Experience
You could use itertools' product() function to do this. The code:
The output of running:
make_truth_table(3)
will be:
A brief explanation: the product() function produces all possible tuples made from its input items, which in this case are the one-character strings 'T' and 'F'. The "repeat" argument to product() tells it how many items to put in each tuple.
product() returns an iterator, which I named 'iter' (you could name it 'dead_parrot'; the effect would be the same). The iterator by itself doesn't produce anything; it just waits for someone to call the Python built-in function next() on it -- say, next(iter).
That "someone", in the above code, is the for ... in loop. The loop knows how to retrieve values, for example ('T', 'T', 'T'), from iter. When iter runs out of values, in this case when all three-letter combinations of 'T' and 'F' have been output, it raises a StopIteration exception. The for ... in loop understands the meaning of the exception, and stops asking for and retrieving values.