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

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:
        print('42')
    elif d and c:
        print('yes')
    print('yes')
elif d and c or b:
    if b and not d or d:
        print('python')
    print('yes')
else:
    print('42')

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:

python
yes

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