Home > Blockchain >  Using multipe operators in Python sequentially
Using multipe operators in Python sequentially

Time:12-24

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.

CodePudding user response:

To understand how those expressions are evaluated you can use 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.

CodePudding user response:

I strongly recommend you to look at the concept of interpreter and stack. And you may research for programming languages concepts. This question is more of a question of how a programming language works.

Python read the line left to right. Let's assume we have a stack. Python read first value and check it's type if numeric or operator.

For example 2 -3 saved to stack

  1. step we got 2 (read line until operator)

  2. step: we got operator (we and python already know if the operator is *, we should check coming char is * because ** another operator). Saved to stack

  3. step: we got - operator. But we can not use with another operator. So we should check if this operator shows us number is negative or positive. saved to stack -> -3

  4. step: no coming char. So we have valid command. Otherwise we could throw exception (eg. SyntaxError)

  5. step: calculate stack

This is basically how mathematical operations are done. Of course there are more of them.

  • Related