Image from WikiMedia, Public Domain

Who’s On First?

A Python Brain Teaser

Miki Tebeka
The Pragmatic Programmers
3 min readApr 14, 2022

--

https://pragprog.com/newsletter/

You’re helping your nephew with his math homework. The homework is about exponents. To impress him — you open the Python prompt and write:

What? You decide to explore this problem later. In the meantime, you fetch and a pen and paper and continue to help your nephew. After your nephew goes home (all his homework done), you have an idea. You open the Python prompt and write:

Ah! Order of operations, is what’s happening. In Python, the ** operator happens before the -. What Python does is -(2**2). Now it makes sense.

You might remember the PEMDAS acronym from school, which stands for parentheses, exponents, multiplication/division, addition/subtraction. Python has more operators, and even though their order is well defined, it is difficult to remember.

Some languages use prefix notation, and then you don’t need to remember operator precedence. Here’s the same code in common Lisp (sbcl):

However writing math in this form is not natural to use. The expression 2*3+4 is written in prefix notation as (+ (* 2 3) 4) — easier for computers, but harder for us humans.

In Python, most of the time you don’t need to place parenthesis around everything. But in some cases you’ll need to use parenthesis to make the code “behave.” Make sure to test your code! Luckily for you, Python comes with an interactive prompt so you can quickly test out your assumption.

You can also use the ast module to see the syntax tree that Python builds from your code. Here’s an example using ast from the command line:

You can see that the UnaryOp (the -) wraps the BinOp (the **).

Another tool you can try out is black, which automatically formats your code.
If you run black on code containing -2**2, black will transform it to -(2**2).

Just like math, the order of operations is important in programming as well. Try to refresh your memory about the order of operations from time to time, and when in doubt — use parenthesis :)

--

--