Looking for a slick way to classify relationship between two numbers, without tons of if/else

Paul Rubin http
Tue Jul 7 03:38:50 EDT 2009


palewire <ben.welsh at gmail.com> writes:
> In my application, I'd like to have a function that compares two values,
> either of which may be null, and then classify the result depending on
> whether one is higher or lower than the other.

Didn't we just have a huge thread about that?  Using a special null
value is often (not always) a code smell.  But anyway (untested):

    def compare(a,b):
       if a is None and b is None:  # I'm guessing you meant this
           return "No data"
       if a == b:
           return "Stayed the same" if a != 0 else "Never had"
       elif a < b:
           return "gained"
       else:
           # we know here that a > b
           return "Lost some" if b > 0 else "Lost all"

I don't know what you intended to do in the case where exactly one of
(a,b) is None, so I'll leave that to you.



More information about the Python-list mailing list