How Does “And Precedence” Work in a Python Boolean Expression?

Rate this post

In Python, the Boolean and operator takes precedence before the Boolean or operator. How does this work exactly?

Consider the following example code puzzle:

# Brain Puzzle
a, b, c, d = True, True, True, False

if b and not d and a and not b:
    if b or a:
    elif d and c:
elif d and c or b:
    if b and not d or d:

Before you read on, take a guess: What’s the output of this code puzzle? (You can solve the puzzle interactively at the Finxter app.)

The puzzle tests your understanding of the precedence logic: and before or.

One of my “Coffee Break Python” email course members Paul asked the following great question regarding this puzzle:

“Thanks for these puzzles โ€“ theyโ€™re keeping my brain working.

With this one, could you provide a couple of lines about the precedence of logical operation evaluation without parentheses. As thatโ€™s the point of this, I believe. I got this wrong so I look to your explanation. You say what (A) means, and โ€˜andโ€™ and โ€˜notโ€™. But the issue is how these combine. Working backwards from the answer, the code obviously falls into the elif block and then runs both elements. But why?

Thanks, Paul”

An excellent question! Here’s the execution flow of the puzzle:

The important part is the elif statement where I indicated the precedence logic by using the brackets: the expression d and c or b is semantically equivalent to the expression (d and c) or b.

Hence, the output of the code puzzle is:


Where to go from here?

If you have difficulties understanding these basic logics statements, consider the book “Coffee Break Python Workbook” which contains many practical code puzzles like this one. This will improve your rapid code understanding skills.

Leave a Comment