samedi 22 mai 2021

Python: Solve this messy if else structure better

I've been stuck on this for a while. I haven't actually written this code yet, but if I were to it would look something like this;

i = 0  # this is an int I get from somewhere else
s = "" # this is the string that I ultimately want to use for something
if i < 1:
    s = "string1"
elif i < 5:
    s = "string2"
elif i < 17:
    s = "string3"

and so on. Basically I want to assign a different string to assign different strings to different intervals and depending on which interval i falls in, I assign the corresponding string to s.

The example above is really messy and looks like a pain to expand/change. I was thinking this could be somehow solved with a dict, but I can't quite seem to figure it out.

Aucun commentaire:

Enregistrer un commentaire