2

Can somebody explain me why Why print(5 ** 2 ** 0 ** 1) = 5 in Python?

I am trying to learn the language and somehow I am not quite sure how this math is done.

Thank you in advance.

1
  • 1
    Well, in regular math we don't write exponentiation linearly. We write them as superscripts. Jul 13, 2022 at 21:57

4 Answers 4

10

Because, like many languages, the exponentiation operator binds right-to-left:

5 ** 2 ** (0 ** 1)
==
5 ** (2 ** 0)
==
5 ** 1
==
5
6

Exponentiation is right-associative, so your expression is the same as

5 ** (2 ** (0 ** 1))
   == 5 ** (2 ** 0)
   == 5 ** 1
   == 5

where any integer raised to the zeroth power is 1 by definition.

3

Others have already pointed this out already, but I just wanted to mention the documentation. You can see this by typing help("OPERATORS") in your repl. There you will spot somewhere at the top:

Operators in the same box group left to right (except for exponentiation, which groups from right to left).

You are right to be surprised though, this seems like a very odd decision to me. In other languages, e.g. octave, 5 ^ 2 ^ 0 ^ 1 == 1 as you'd expect. Oddly enough, both Julia and R agree with python on this.

EDIT: On second thought, I suppose making exponentiation right-associative makes sense too; you would expect to mean 5^8 rather than 25^3 ...


Incidentally, here's another trap. How much is: 5 * -1 ** 2 ? Is it 5 or -5?

See help("**") to see why it is what it is. (incidentally, this is how octave, R, and julia treat this case too).

The moral of the story is: always group when there is potential for ambiguity. Or at least check the precedence is what you think it is before ungrouping.

2

** is exponentiation.

0 raised to the power of 1 is 0. So, we could re-write the statement as print(5**2**0) without changing the result.

2 raised to the power of 0 is 1. So, we can re-write the statement as print(5**1) without changing the result.

5 raised to the power of 1 is 5. So, we can rewrite the statement as print(5) without changing the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.