vendredi 5 février 2021

How to avoid very long if-elif-elif-else statements in Python function

Is there a smart way to shorten very long if-elif-elif-elif... statements?

Let's say I have a function like this:

def very_long_func():
  something = 'Audi'
  
  car = ['VW', 'Audi', 'BMW']
  drinks = ['Cola', 'Fanta', 'Pepsi']
  countries = ['France', 'Germany', 'Italy']
  
  if something in car:
    return {'type':'car brand'}
  elif something in drinks:
    return  {'type':'lemonade brand'}
  elif something in countries:
    return {'type':'country'}
  else:
    return {'type':'nothing found'}
  

very_long_func()
>>>> {'type': 'car brand'}

The actual function is much longer than the example. What would be the best way to write this function (not in terms of speed but in readability)

I was reading this, but I have trouble to apply it to my problem.

Aucun commentaire:

Enregistrer un commentaire