Why -1**0 = -1 in python?

Viewed 79

Why does this code in python return -1 instead of 1?

-1**0

I have checked it in several versions of python, but still nothing.

2 Answers

Perhaps you should try the math.pow function

>>> import math
>>> math.pow(-1, 0)
1.0

Or correctly group the operators; exponents happen before negation

>>> (-1) ** 0
1

the hint is in the ast expansion:

$ pip install astpretty
...
$ astpretty t.py --no-show-offsets
Module(
    body=[
        Expr(
            value=UnaryOp(
                op=USub(),
                operand=BinOp(
                    left=Constant(value=1, kind=None),
                    op=Pow(),
                    right=Constant(value=0, kind=None),
                ),
            ),
        ),
    ],
    type_ignores=[],
)

-1**0 is best interpreted as - (1 ** 0) -- applying a unary negation to a power

Related