在python中,++x是正确的语法。“++x”是什么意思?

2024-04-25 01:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Python: Behaviour of increment and decrement operators

>>> a=2
>>> ++a
2
>>> a++
Traceback (  File "<interactive input>", line 1
    a++
      ^
SyntaxError: invalid syntax
>>> ++a
2

为什么++x可以?在

(我之所以问这个问题,是因为工作中有人习惯性地编写了++I,这并不像(习惯性地)期望的那样,但也没有抛出错误,所以花了一些时间才找到错误。)


Tags: andofinput错误lineinteractivefiletraceback
1条回答
网友
1楼 · 发布于 2024-04-25 01:42:12

可能是Python: Behaviour of increment and decrement operators的重复项。在

虽然我找不到操作人员确切推理的文档,但我将引用链接问题中已接受答案的一部分,我认为是这样:

  • 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 += 1 into the inc 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.
网友
2楼 · 发布于 2024-04-25 01:42:12

它相当于+(+a)

>>> +-2
-2
>>> -+2
-2
>>>  2
2
>>> ++++-2
-2
网友
3楼 · 发布于 2024-04-25 01:42:12

它的意思是+(+a),即与{}的意思相反(尽管在这个例子中,结果显然是一样的!)在

http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex。在

相关问题 更多 >