2020-12-01 07:59:34
Python
, 2020-12-01 07:59:34

Are there nicer constructions than if elif else where a different action should be performed on each value?

I don’t really like how the execution of this kind of code looks like, where there is a value and depending on what this value is, a certain action needs to be performed. I would like to know if there are designs that are more efficient or more understandable than those that I use. Below is an example, an excerpt from the class.

def gamble(self):
dice = randint(1,6)
if dice == 1:
self.pass_day()
elif dice == 2:
self.eat_food()
elif dice == 3:
self.work_day()
elif dice = = 4:
self.have_fun()
elif dice == 5:
self.go_shopping()
else:
self.sleep()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-12-01
Nurdaulet Turar

Yes, all this can be replaced with a dictionary{1: ссылка_функцию1, 2: ссылка_функцию2}

A
Alexey Cheremisin, 2020-12-01
@leahch

For this, it is better to use the dictionary function

def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found
...
f('c') # 9
f('a') # 1
f('b') # 3

Well, there are a lot of options - https://ru.stackoverflow.com/questions/460207/%D0%...
def get_temp_description(temp):
    return {
               temp < -20: 'Холодно',
        -20 <= temp < 0:   'Прохладно',
          0 <= temp < 15:  'Зябко',
         15 <= temp < 25:  'Тепло',
         25 <= temp:       'Жарко'
    }[True]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question