Is using "if/Elif/Else" with Return good programming practice?

Asked

Viewed 677 times

1

Ex.:

return (sum*2 if a == b else sum)
  • If the question is of if, Elif and Else is duplicate of Why should I only use a "Return" in each function? - which is different from your example.

  • 1

    Now, if you want to know if inline only, it would be good to leave specific (ai is not duplicate, is a problem apart even, but still is strange, because what problem would have, or what would be the difference to the multiplication used?)

  • 1

    Do you have any specific reason for asking this question? Have you seen it somewhere? Can you see any problems?

  • Just to clarify: the if block is flow control, the inline is already an operator.

  • I just wanted to know if using Return with if and Else instead of blocks of code (as answered below) decreases the quality of the code, gets confused in readability.

1 answer

3

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

But if you are in the sense of blocks I don’t see much problem, what I would change would be just a detail, in case there is if, Elif and Else to occur processing, define an initial value for the variable and depending on the flow you take will override the value , with this only return 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 may occur the discount value changes.. And only the end do the final calculation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.