How do I use pre-increment/decrement operators (
--), just like in C++?
++count run, but not change the value of the variable?
++ is not an operator. It is two
+ operators. The
+ operator is the identity operator, which does nothing. (Clarification: the
- unary operators only work on numbers, but I presume that you wouldn’t expect a hypothetical
++ operator to work on strings.)
Which translates to
You have to use the slightly longer
+= operator to do what you want to do:
count += 1
I suspect the
-- operators were left out for consistency and simplicity. I don’t know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
- Simpler parsing. Technically, parsing
++countis ambiguous, as it could be
+operators) just as easily as it could be
++operator). It’s not a significant syntactic ambiguity, but it does exist.
- Simpler language.
++is nothing more than a synonym for
+= 1. It was a shorthand invented because C compilers were stupid and didn’t know how to optimize
a += 1into the
incinstruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
- Confusing side-effects. One common newbie error in languages with
++operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language “gotcha”-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.