vendredi 23 juillet 2021

Minimizing if statement that contains and is conditioned on an expression

I often have to write lines such as:

if exp(var1):
   new_variable = exp2(exp(var1))

As you can see, this statement evaluates the exp twice - one for the condition and then within the body of the statement. Is there a neat pythonic way to write this so that the exp is evaluated only once? I know that I can write:

temp_variable = exp(var1)

if temp_variable:
     new_variable = exp2(temp_variable)

but this introduces a new variable. My question specifically is if there is a solution that's more elegant than this one.

Aucun commentaire:

Enregistrer un commentaire