简体   繁体   English

(-) 运算符如何将负数转换为正数?

[英]How the (-) operator converting negative numbers to positive works?

Here is an example:这是一个例子:

def absolute(x):
    if x >= 0:
        return x
    else:
        return -x

print(absolute(3))
print(absolute(-119))

The Output: Output:

3
119

Now, how -119 became a positive number by just using the (-) subtraction operator?现在,仅使用 (-) 减法运算符, -119是如何变成正数的?

Thanks.谢谢。

Update:更新:

For those who misunderstood my q,对于那些误解我的q的人,

So I'm repeat, How -119 turns to be 119 by using the (-) operator!所以我再说一遍,-119 如何通过使用 (-) 运算符变成 119! as in return -x in the code above.如上面代码中的return -x一样。 Nope, I know it would be a multiplication but how it is achieved by using (-) operator?不,我知道这将是一个乘法,但它是如何通过使用 (-) 运算符来实现的?

You seem to be confusing the binary operator x - y aka "x subtract y" with the unary operator -x aka "negate x".您似乎将二元运算符x - y又名“x 减 y”与一元运算符-x又名“否定 x”混淆了。 They are different things.它们是不同的东西。

-x returns the negation of x . -x返回x的否定。 If x is positive, -x is negative, and vice versa.如果x为正,则-x为负,反之亦然。

Unary - is: https://docs.python.org/3/library/operator.html#operator.neg一元-是: https://docs.python.org/3/library/operator.html#operator.neg

Binary - is: https://docs.python.org/3/library/operator.html#operator.sub二进制-是: https://docs.python.org/3/library/operator.html#operator.sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 range() 函数中的负数 - 如何从正数打印到负数? - Negative numbers in range() function - how to print from positive to negative numbers? 如何在 Python 中将正数转换为负数? - How to convert positive numbers to negative in Python? 在有正数和负数的 dataframe 中,如何将正数向上舍入和将负数向下舍入(均为 5 的倍数)? - In a dataframe with both positive & negative numbers, how to round positive numbers up and round negative numbers down (both to multiples of 5)? re.findall 与负数,我的代码只适用于正数 - re.findall with negative numbers, my code only works on positive numbers 负数和正数之间的按位 AND (&)? - Bitwise AND (&) between negative and positive numbers? 如何从列表中计算每个集合中的负数和正数? - how to count negative and positive numbers in each set from a list? 如何根据出现的行总结列表中的负数和正数 - How to sum up negative and positive numbers in a list based on the row they occur 如何将包含正数和负数的数据归一化为0和1? - How to normalize data which contain positive and negative numbers into 0 and 1? 如何改善这种检查两个数字都是正数还是负数的模式? - How to improve this pattern of checking if two numbers are both positive or negative? 在 pandas 中应用 groupby 后如何计算列的正数和负数 - how to count positive and negative numbers of a column after applying groupby in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM