My problem started when I made an error when creating an index count for a for loop and I found a behavior in Python 3.4 that I did not understand.
> a = 1
> a =+ 2 #reversed 'plus and equal'
> a
2
> a += 2 #correct 'plus and equal'
> a
> a
4
At first I thought that this mistake should have returned an error, but I started thinking that the reversed 'plus and equal' logic may be instead interpreted as variable 'a' is equal to a positive integer '2'. To confirm this I tried setting a variable to a negative integer and then used it to change the sign of a variable.
> a =- 2
> a
-2
> a =- a
> a
2
> a = -a
> a
-2
This all left me wondering why a unary operator does not need to be adjacent to the integer or variable that is being changed.
Python reads right to left, in that what's on the right side of the equals gets interpreted first so you have the two sides:
(a) =(+ 2)
Whitespace is free space, so regardless of the whitespace the interpreter will still read lines of code as if the whitespace were not there. As such, Python interprets it as equals +2 so, it's just like making an integer positive (or negative if you do equals minus 2)
>>> a =+ 2 # note the whitespace
>>> a
>>> 2
>>> a = +2 # consistent interpretation
>>> a
2
>>> a =- 2 # no matter where
>>> a
-2
>>> a = -2 # the whitespace is
>>> a
-2
It's like how you don't have to have a space between around the equals when assigning. e.g:
a = 1
is the same as
a=1
The interpreter reads it in the appropriate order and manipulates the information as it interprets it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With