One line if assignment in python

4.2k Views Asked by At

following this topic One line if-condition-assignment

Is there a way to shorten the suggested statement there:

num1 = (20 if intvalue else 10)

in case that the assigned value is the same one in the condition?

this is how it looks now:

num1 = (intvalue if intvalue else 10)

intvalue appears twice. Is there a way to use intvalue just once and get the same statement? something more elegant?

1

There are 1 best solutions below

6
On BEST ANSWER

You can use or here:

num1 = intvalue or 10

or short-circuits; if the first expression is true, that value is returned, otherwise the outcome of the second value is returned.