Home > Blockchain >  Is there a way in python to execute a statement like 'for min(x, y) do z' without an if-el
Is there a way in python to execute a statement like 'for min(x, y) do z' without an if-el

Time:10-25

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

To demonstrate my question I will use the following pseudo-code example:

a = 10
b = 15

c = None


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

My question is: 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 would be much appreciated.

CodePudding user response:

You can use an inline if conditional

c = a if a< b else b

Be mindful that your implementation misses the case of a=b.

Using min is also an option

c = min(a,b) 

CodePudding user response:

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

  • Related