Skip to content
Advertisement

Using multipe operators in Python sequentially

I’m trying to understand how Python handles using multiple sequential operators to add and subtract numbers.

Here is an example of what I mean:

>>> 5+-2
3
>>> 5-+2
3
>>> 5+-+-+2
7
>>> 5+-+-+-2
3
>>> 5+-+---+2
7
>>> 5-+-+---+2
3
>>> 5-+-+---+-2
7
>>> 5++++-++++--+-+++2
7
>>> 5+----2
7
>>> 5++++-2
3
>>> 5++-++-2
7
>>>

I don’t understand what decides whether to add or subtract these two integers.
I’ve used Python 3.11.1 for this example.

Advertisement

Answer

To understand how those expressions are evaluated you can use the ast (abstract syntax tree) module.

>>> import ast
>>> def pretty_print_ast(code: str) -> None:
...     print(ast.dump(ast.parse(code), indent=4))

Now let’s ask how Python evaluates 5+-2?

>>> pretty_print_ast("5+-2")
    Module(
        body=[
            Expr(
                value=BinOp(
                    left=Constant(value=5),
                    op=Add(),
                    right=UnaryOp(
                        op=USub(),
                        operand=Constant(value=2))))],
        type_ignores=[])

So it’s getting parsed as 5+(-2). Now let’s take another example 5+-+-+2.

>>> pretty_print_ast("5+-+-+2")
Module(
    body=[
        Expr(
            value=BinOp(
                left=Constant(value=5),
                op=Add(),
                right=UnaryOp(
                    op=USub(),
                    operand=UnaryOp(
                        op=UAdd(),
                        operand=UnaryOp(
                            op=USub(),
                            operand=UnaryOp(
                                op=UAdd(),
                                operand=Constant(value=2)))))))],
    type_ignores=[])

As you can see, it’s getting parsed as 5+(-(+(-(+2)))).

Please note that the UnaryOp node in the ast corresponds to the unary operations.

Advertisement