Possible Duplicate:
Python Ternary Operator
In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression.
For example,
return (i < x) ? i : x
This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows.
if (i < x) return i else return x
Is it possible to use this syntax in python and if so, how?
Python bool() Function The bool() function returns the boolean value of a specified object. The object will always return True, unless: The object is empty, like [], (), {} The object is False. The object is 0.
It returns False if the parameter or value passed is False.
Booleans represent one of two values: True or False .
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.
You can use (x if cond else y)
, e.g.
>>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a
That will work will lambda function too.
Yes, it looks like this:
return i if i < x else x
It's called the conditional operator in python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With