[PYTHON] There are times when you can shorten the if statement using max · min

I noticed that I wrote some python code, so make a note. It may be a rudimentary and common sense technique, but ...

Consider a case where you want to branch a variable called a depending on whether the result (some_condition + add_value) of a certain formula is larger than CONSTANT.

For the time being, I will write it appropriately with an if statement.

python


a = 0
if some_condition + add_value < CONSTANT:
    a = some_condition + add_value
else:
    a = CONSTANT

... I think it's too verbose, so I'll put the else operation in the initialization (variable declaration).

python


a = CONSTANT
if  some_condition + add_value < CONSTANT:
    a = some_condition + add_value

After doing this, I realized that all I had to do was compare some_condition + add_value with CONSTANT, so I used min to do just one line.

python


a = min(some_condition + add_value, CONSTANT)

There is no ternary operator in python, and the code tends to be long at the time of conditional branching, but if you use min / max, the code may be a little cleaner.

Recommended Posts

There are times when you can shorten the if statement using max · min
About the development environment you are using
Check the type of the variable you are using
Determining if there are birds in the image
What are you using when testing with Python?
What to do if you get the error ʻERR_FEATURE_UNAVAILABLE_ON_PLATFORM` when using ts-node-dev on Linux
Solution if you crash when using selenium on heroku
How to turn the for statement when there are multiple values for one key in the dictionary
(Python3) No. oO (Are you using the standard library?): 5 shaders
If you think that the person you put in with pip doesn't work → Maybe you are using python3?