In Python, you can negate a number (i.e. convert a positive number to negative, and a negative to positive) in the following ways:
Using Unary Minus Operator
You may negate a number using the unary minus operator (-
) like so:
-n
This would convert a positive number to a negative number, and a negative number to a positive number. For example, you can use this in the following way:
def negate(num): return -num print(negate(1234)) # -1234 print(negate(-1234)) # 1234
0
is a special case, which would always return 0
when negated:
# ... print(negate(0)) # 0 print(negate(-0)) # 0
Using Arithmetic Operators
You may convert a positive number to negative or vice versa by simply multiplying it by -1
:
n * -1
It would also work if you divide the number by -1
(but you will have to convert the result to int as it would return a float):
int(n / -1)
Alternatively, you may subtract the number from 0
:
0 - n
You could use any of these to convert a positive number to a negative number and vice versa, for example, like so:
def negate(num): return num * -1 print(negate(1234)) # -1234 print(negate(-1234)) # 1234
def negate(num): return int(num / -1) print(negate(1234)) # -1234 print(negate(-1234)) # 1234
def negate(num): return 0 - num print(negate(1234)) # -1234 print(negate(-1234)) # 1234
In any case, 0
would always return 0
when negated:
# ... print(negate(0)) # 0 print(negate(-0)) # 0
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.