Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "++" operator doesn't work [duplicate]

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?

like image 816
user469652 Avatar asked Nov 27 '22 23:11

user469652


2 Answers

There isn't a ++ operator in python. You're applying unary + twice to the variable.

like image 56
Nick T Avatar answered Dec 05 '22 03:12

Nick T


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]
like image 39
Seth Johnson Avatar answered Dec 05 '22 04:12

Seth Johnson