Home > other >  Why print(5 ** 2 ** 0 ** 1) = 5 in Python?
Why print(5 ** 2 ** 0 ** 1) = 5 in Python?

Time:07-14

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.

CodePudding user response:

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

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

CodePudding user response:

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.

CodePudding user response:

** 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.

CodePudding user response:

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.

  • Related