Possible Duplicate:
Python: Behaviour of increment and decrement operators
Hi, I've tried this.
++num
and the num doesn't change at all, always show the value when initialized
if I change ++num
to num+=1
then it works.
So, my question is how that ++
operator works?
There isn't a ++
operator in python. You're applying unary +
twice to the variable.
Answer: there is no ++
operator in Python. += 1
is the correct way to increment a number, but note that since integers and floats are immutable in Python,
>>> a = 2
>>> b = a
>>> a += 2
>>> b
2
>>> a
4
This behavior is different from that of a mutable object, where b
would also be changed after the operation:
>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]
>>> a
[1, 2]
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