Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pythonic way of writing a long if-else statement?

Tags:

python

I am quite new to Python though I have had experience in Java before.

I have the following code to convert a score into an interval delta (as part of a Spaced Repetition System (SRS) program I am implementing). This code looks ugly and not very readable. Typically I would have used a switch statement in Java. But in python I could not find an equivalent. Hence I have written this code which produces the result. But I want to take this opportunity to learn different options for achieving the same output using more pythonic ways. I would appreciate any help, even if they are pointers to resources that I can read to improve this code.

   # Convert score into an interval delta
    if score == 0:  # Perfect page
        intervalDelta = +3
    elif score == 1:  # 1 Word Mistake
        intervalDelta = +2
    elif score <= 3:  # 3 Word Mistakes
        intervalDelta = +1
    elif score == 4:  # 1 Line Mistake
        intervalDelta = 0
    elif score <= 8:  # 2 Line Mistakes
        intervalDelta = -1
    elif score <= 12:  # 3 Line Mistakes
        intervalDelta = -2
    elif score <= 20:  # 5 Line Mistakes
        intervalDelta = -3
    elif score <= 30:  # 7.5 Line Mistakes - Half a page
        intervalDelta = -5
    else:  # More than half a page
        intervalDelta = -7
like image 583
Siraj Samsudeen Avatar asked Mar 04 '23 02:03

Siraj Samsudeen


1 Answers

I don't find the long if statement that unreadable, although I'd change to using <= for consistency (since the == cases are already single possibilities using <=). If I were implementing it from scratch, I'd probably write something like the following simply to have the associations more visible:

from math import inf


SCORE_DELTAS = (
    (0, +3),
    (1, +2),
    (3, +1),
    (4, +0),
    (8, -1),
    (12, -2),
    (20, -3),
    (30, -5),
    (inf, -7),
)


def score_to_delta(score):
    for bound, delta in SCORE_DELTAS:
        if score <= bound:
            return delta
like image 72
asthasr Avatar answered May 11 '23 00:05

asthasr