1

Given variables a, b:

b = 3

a = b++

a = --b

How do you write this correctly in Python?

3 Answers3

10

From The Zen of Python:

Explicit is better than implicit

So, let's write:

b = 3
a = b; b +=1
b -= 1; a = b
Don
  • 16,928
  • 12
  • 63
  • 101
5

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
St. Hand
  • 134
  • 6
2

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
jackcogdill
  • 4,900
  • 3
  • 30
  • 48