Behaviour of increment and decrement operators in Python
Behaviour of increment and decrement operators in Python
How do I use pre-increment/decrement operators (++
, --
), just like in C++?
Why does ++count
run, but not change the value of the variable?
回答1
++
is not an operator. It is two +
operators. The +
operator is the identity operator, which does nothing. (Clarification: the +
and -
unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++
operator to work on strings.)
++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer +=
operator to do what you want to do:
count += 1
I suspect the ++
and --
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
++count
is ambiguous, as it could be+
,+
,count
(two unary+
operators) just as easily as it could be++
,count
(one unary++
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 optimizea += 1
into theinc
instruction 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.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-09-17 向量内积(点乘)和外积(叉乘)概念及几何意义
2021-09-17 jQuery Migrate
2021-09-17 Best way to expose resource strings to JavaScript files in ASP.NET MVC?
2021-09-17 What's the difference between sweetalert and sweetalert2?
2021-09-17 Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]
2021-09-17 sweetalert2 and xss
2021-09-17 上海居住证办理条件以及流程?