How to Always Return a Negative Number in Python?

Find out how to convert positive numbers to negative and leave negative numbers unchanged

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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.