为什么 1+++2 = 3?
Python 如何计算表达式1+++2
?
我在中间放置了多少个 +
,它打印 3
作为答案。 请任何人都可以解释一下这种行为
对于 1--2
,它正在打印 3
,对于 1---2
,它正在打印 -1
How does Python evaluate the expression 1+++2
?
How many ever +
I put in between, it is printing 3
as the answer. Please can anyone explain this behavior
And for 1--2
it is printing 3
and for 1---2
it is printing -1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的表达式与以下内容相同:
任何数字表达式都可以在
-
前面添加以使其为负数,或者在+
前面添加不执行任何操作(该选项是为了对称而存在的)。 带负号:我
看到你澄清了你的问题,说你来自 C 背景。 在 Python 中,没有像 C 中的
++
和--
这样的增量运算符,这可能是您感到困惑的根源。 要在 Python 中递增或递减变量i
或j
,请使用以下样式:Your expression is the same as:
Any numeric expression can be preceded by
-
to make it negative, or+
to do nothing (the option is present for symmetry). With negative signs:and
I see you clarified your question to say that you come from a C background. In Python, there are no increment operators like
++
and--
in C, which was probably the source of your confusion. To increment or decrement a variablei
orj
in Python use this style:额外的 + 不是增量器(如 C++ 中的 ++a 或 a++)。 他们只是表明这个数字是正数。
不存在这样的 ++ 运算符。 但有一元 + 运算符和一元 - 运算符。 一元 + 运算符对其参数没有影响。 一元 - 运算符对其运算符求反或将其乘以 -1。
-> 1-
> 1
相同
与 +(+(1)) -> 3
因为它与 1 + (+(+(2)) 相同,
同样你可以用 --1 来表示 - (-1),即 +1。
-> 1
为了完整性,没有 * 一元运算符。所以 *1但有一个错误。
运算符是 of 的幂,它需要 2 个参数。
-> 8
The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.
There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1.
-> 1
-> 1
This is the same as +(+(1))
-> 3
Because it's the same as 1 + (+(+(2))
Likewise you can do --1 to mean - (-1) which is +1.
-> 1
For completeness there is no * unary opeartor. So *1 is an error. But there is a **
operator which is power of, it takes 2 arguments.
-> 8
1+(+(+2)) = 3
1 - (-2) = 3
1 - (-(-2)) = -1
1+(+(+2)) = 3
1 - (-2) = 3
1 - (-(-2)) = -1
尝试一元加法和一元减法:
Trying Unary Plus and Unary minus:
我相信它被解析为,第一个 + 作为二元运算(加),其余的作为一元运算(取正)。
I believe it's being parsed as, the first + as a binary operation (add), and the rest as unary operations (make positive).
将其视为 1 + (+1*(+1*2)))。 第一个 + 是运算符,后面的加号是第二个操作数的符号 (= 2)。
就像 1---2 与 1 - -(-(2)) 或 1- (-1*(-1*(2)) 相同
Think it as 1 + (+1*(+1*2))). The first + is operator and following plus signs are sign of second operand (= 2).
Just like 1---2 is same as 1 - -(-(2)) or 1- (-1*(-1*(2))