0

I am trying to return an absolute value of a number but make it so when a string is used, it prints 'None'. However, I get the error 'UnboundLocalError: local variable 's' referenced before assignment'.

def absolute_value_safe(value):
    if type(value) == str:
        print ('None')
    else:
        s= abs(value)
    return s
that other guy
  • 109,738
  • 11
  • 156
  • 185
JPlummz
  • 13
  • 2
  • FWIW, doing `type(something) == some_type` is not considered good form. Usually, you'll want to use `isinstance(something, some_type)` – mgilson Jan 19 '16 at 22:46

1 Answers1

0

If the first case of the condition triggers, s is not assigned so return s isn't well defined.

Just make sure it's always assigned before returning it:

def absolute_value_safe(value):
    if type(value) == str:
        print ('None')     # Was this even intended to be here?
        s = None
    else:
        s= abs(value)
    return s
that other guy
  • 109,738
  • 11
  • 156
  • 185