mercredi 28 juin 2017

Python - too many 'elif: return()' statements?

I have ths function that's passed two arguments:

def function(a, b):
    if   a == 'd' : return(4*b)
    elif a == '!' : return(5)
    elif a == 'k' : return(1-2*k+k**2)
    elif a == 'Z' : return(1/k)
    (...)

a is checking it's equality to a single character, and b is always a number; the function always returns a number as well. Sometimes it's not always a simple return though.

def function(a, b):
    (...)
    elif a == '2':
        temp_b = foo(b)
        if b == 2 : temp_b += 2
        return(temp_b)

I have a very long list of elif statements, is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire