Python – How to Get the Sign of a Number

Update:
Here’s a better way provided by Florent Guillaume:

def sign(number):return cmp(number,0)

Here is my original method:

def sign(number):
    """Will return 1 for positive,
    -1 for negative, and 0 for 0"""
    try:return number/abs(number)
    except ZeroDivisionError:return 0

It’s just a function I’ve been thinking would be included somewhere in Python but haven’t been able to find. It’s simple but _I_ searched for it so enjoy!

Terms I searched for:

  1. python get sign of a number
  2. python “get sign”

2 Responses to “Python – How to Get the Sign of a Number”

  1. Florent Guillaume says:

    A division just to get the sign? Sheesh.

    Here’s a better way: return cmp(number, 0)

  2. Indeed, that’s much better. I just didn’t think of that.

    Thanks!