Given variables a
, b
:
b = 3
a = b++
a = --b
How do you write this correctly in Python?
From The Zen of Python:
Explicit is better than implicit
So, let's write:
b = 3
a = b; b +=1
b -= 1; a = b
There are no increment/decrement (++
/--
) operators in Python. This is because integers in Python are immutable (can't be modified, only reassigned). So let's break this down and emulate their behavior.
What does b++
do? It evaluates to b
, then increments b
. Therefore, we write this as:
a = b
b += 1
Now onto --b
. It decrements b
, then evaluates to the new value of b
. In Python:
b -= 1
a = b
Put it all together and we get:
b = 3
a = b
b += 1
b -= 1
a = b
In Python, you cannot do b++
. There is no plus plus.
There is the operator +=
, so you could this kind of stuff:
b = 3
b += 1
b -= 1
Or simply:
b = 3
a = b + 1
a = b - 1