Home > database >  Shorthand for many if statements
Shorthand for many if statements

Time:12-07

I need to do a lot of if statements to determine the way certain data is going.

if mean > 75 and avg <= 5:
  output = 'A'
elif mean > 75 and avg > 5:
  output = 'B'
elif mean > 75 and avg < -5:
  output = 'C'
elif mean > 65 and avg <= 5:
  output = 'D'
elif mean > 65 and avg > 5:
  output = 'E'
etc...

I found another article on Stack Overflow for this problem, but it's for a lot simpler if statements, using only one variable and using each number once. In my example I use single characters, but in the real application I need to use long strings that explain exactly what the numbers mean.

Is there any way I can do what the post I linked does, but using the numbers three times and negating it once like in my example?

CodePudding user response:

If you're willing to use the newest version 3.10, then you should definitely take a look of the new match statements.

CodePudding user response:

One simple solution is to build a list of test cases and results.

tests = {(75,5):["Good","Bad","Ugly"],
         (65,5):["Red","Amber","Green"]}

def test(mean, avg, test_cases):

    for test_case, test_results in test_cases.items():
        
        mean_test, avg_test = test_case
                
        if mean > mean_test:
            if avg <-avg_test:
                return test_results[0]

            if avg <=avg_test:
                return test_results[1]
       
            return test_results[2]
    return None

print(test(79,-5,tests))
             

CodePudding user response:

You could compute the output without so many ifs using lists of values in which you compute an index (using next() on a comprehensions or some other calculation):

means  = [75,65,55,...]                     # breakpoints of mean
scores = [("A","B","C"),("D","E","F"),...]  # values for mean/avg combinations

iMean  = next(i for m in enumerate(means) if mean>m) # index in means
iAvg   = 2 if avg<-5 else 1 if avg>5 else 0          # index in avg group
output = scores[iMean][iAvg]                         # access based on indexes
  • Related