0 Replies - 1691 Views - Last Post: 31 October 2016 - 09:41 AM

#1 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 558
  • View blog
  • Posts: 1,748
  • Joined: 27-December 13

a sign function

Posted 31 October 2016 - 09:41 AM

Neither Python nor the math module has a sign function.
A sign function returns the values -1, 0, +1 depending of the argument is negative, zero or positive.

Here is one:
def sign(x):
    """
    This function returns -1 or 0 or +1 depending of the
    sign of the input; negative, zero or positive.
    
    Type 'complex' is here handled as a non-number.

    'bool' needs to be handled separately (and first) as 'True' and
    'False' is otherwise recognized as numbers 1 and 0 respectively.

    If the input is not a number, the function prints an error
    message and returns 'None'.

    By DK3250, October 2016.
    """
    
    if isinstance(x, (bool)):
        print("In function sign: Value '{}' is 'bool'".format(x))
        return
        
    elif isinstance(x, (int, float)):
        pass
    
    else:
        print("In function sign: Value '{}' is not a number".format(x))
        return
    
    if x > 0:
        return 1
    elif x == 0:
        return 0
    elif x <= 0:
        return -1


#### Test data
##for x in (-2, 0, 5, 'txt', True, False, None, 1, -1, 2j, 0.3, -0.3, 0.0, '', sign):
##    if sign(x):
##        print("input:", x, "sign:", sign(x))




Is This A Good Question/Topic? 0
  • +

Page 1 of 1