Using "if / elif / else" with return is good programming practice? [closed]

0

Eg:

return (sum*2 if a == b else sum)
    
asked by anonymous 24.04.2017 / 01:46

1 answer

2

The only problem I see would be the readability, which in the case you can even understand, but if there are more levels there begins to complicate.

But if you are in the direction of blocks I do not see much problems, what I would change would be just a detail, in case there is if, elif and else to process, I would define an initial value for the variable and depending on the flow that will override the value, so it only returns it at the end, with the value already defined.

Ex:

def get_desconto(compra):

    if compra.valor_total <= 500:
        desconto = 0.05
    elif ( compra.valor_total >= 600 ) and ( compra.valor_total <= 1000 ):
        desconto = 0.1
    else:
        desconto = 0.3

    return desconto * compra.valor_total

With this depending on the flow that can occur the discount value changes .. And only the final I make the final calculation.

    
24.04.2017 / 02:02