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?
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
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?
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