To make sure that you always return a negative number in Python, you can do either of the following:
Using Unary Minus Operator
You can convert the number to its absolute form, and then negate it using the unary minus operator (-
):
-abs(n)
This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use this in the following way:
def neg(num): return -abs(num) print(neg(1234)) # -1234 print(neg(-1234)) # -1234
Using Arithmetic Operators
You can convert the number to its absolute form, and then negate it either by:
- Multiplying or dividing the number by
-1
, or; - Subtracting the number from
0
.
abs(n) * -1
int(abs(n) / -1)
0 - abs(n)
This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use any of these in the following way:
def neg(num): return abs(num) * -1 print(neg(1234)) # -1234 print(neg(-1234)) # -1234
def neg(num): return int(abs(num) / -1) print(neg(1234)) # -1234 print(neg(-1234)) # -1234
def neg(num): return 0 - abs(num) print(neg(1234)) # -1234 print(neg(-1234)) # -1234
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.