Here is an example:
def absolute(x):
if x >= 0:
return x
else:
return -x
print(absolute(3))
print(absolute(-119))
The Output:
3
119
Now, how -119
became a positive number by just using the (-) subtraction operator?
Update:
For those who misunderstood my q,
So I'm repeat, How -119 turns to be 119 by using the (-) operator! as in return -x
in the code above. 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". They are different things.
-x
returns the negation of x
. If x
is positive, -x
is negative, and vice versa.
Unary -
is: https://docs.python.org/3/library/operator.html#operator.neg
Binary -
is: https://docs.python.org/3/library/operator.html#operator.sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.