Is there a way in python to execute a statement like 'for min(x, y) do z' without an if-else logic?

Question:

Is there a shorter way of writing an if-else loop in a scenario where I have a comparison between two numbers as condition?

Here is a pseudo-code example:

a = 10
b = 15

c = None


if a > b:
    c = b
elif a < b:
    c = a    

Is there a way in python to take the expression above and shorten it?

My thoughts so far have lead me to ideas like for min(x, y) do z, but I don’t know if that is implementable in that form in python. Any suggestions?

Asked By: Guy

||

Answers:

Yes there are two ways you could do that. Python has a built in function min() which, like you said, will return the minimum of two values

c = min(a,b)

Or you can put an if in one line like this

c = b if b<a else a

Hope this helps

Answered By: Omar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.