Finding difficulty in understanding basic additions in Python

时间:2017-06-19 13:52:40

标签: python

I am new to python and I'm trying to work on some basic concepts. I tried addition logic in a more random way where I thought I'll get errors. But out of surpize I'm getting output. For example, a++++++++++++++++++ 1 is giving output. So, can any explain what exactly kind of additions are being performed here. Please find the code which I tried.

>>> a++ + 1
4
>>> ++a + 1
4
>>> a++ ++ 1
4
>>> ++a ++ 1
4
>>> a++ +++ 1
4
>>> ++a +++ 1
4
>>> a+++ 1
4
>>> a++++++++ sdjfksdopfjsopdfjsd

Traceback (most recent call last):
  File "<pyshell#112>", line 1, in <module>
    a++++++++ sdjfksdopfjsopdfjsd
NameError: name 'sdjfksdopfjsopdfjsd' is not defined
>>> a++++++++++++++++++++++++++++++++++++
SyntaxError: invalid syntax
>>> a++++
SyntaxError: invalid syntax
>>> a+++
SyntaxError: invalid syntax
>>> a++
SyntaxError: invalid syntax
>>> a++++++++++++++++++++++++++++++++++++++ 1
4
>>> a++ 1
4
>>> a++ + 1
4
>>> ++a
3

2 个答案:

答案 0 :(得分:1)

You can have multiple + and - operators in a row, because they don't represent add/subtract, but rather the positive/negative sign of a number. For example,

a + +1

is adding a and +1 together. The spaces don't matter here, so these are all equilevant:

a + +1
a++1
a + + 1
a+ +1
a++ 1
a        +            +          1

Now, because adding a sign to a number (e.g. +5 or -5) still keeps it as a number, you can reapply another sign to the new number. And another. And another. To infinity.

The negative sign actually changes the number's sign, just like in maths:

>>> x = 5
>>> -x
-5
>>> -(-5)
5
>>> --5  # Unlike maths, we don't need parenthesis
5
>>> -----5
-5

You can do this exact thing with +, it's just that it doesn't do anything:

>>> x = 5
>>> +x
5
>>> ++++x
5
>>> +++++++++++++++++1
1

And now take this number, +++++++++++++++++1, and append it to 3:

>>> 3 + +++++++++++++++++1
4

As you see, there's only one addition operation, and the rest are just unary operators to indicate the sign of the number.

答案 1 :(得分:1)

+ in most of your cases there is simply the unary + operator, not the addition operator or increment operator (the latter of which doesn't exist in Python).

I.e. ++1 is +(+1), which doesn't really do anything. In contrast, the unary - operator does something: -1 is -1, --1 is 1, ---1 is -1.

All the operations that are valid in your example boil down to a + 1 if you remove the redundant + operators.