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:
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?
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.