Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python (bool) ? then : else syntax? [duplicate]

Tags:

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?

like image 832
user1162865 Avatar asked Jan 21 '12 22:01

user1162865


People also ask

What is bool() in Python?

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.

What does bool (' false ') return?

It returns False if the parameter or value passed is False.

What are the two boolean values in Python?

Booleans represent one of two values: True or False .

Is 0 True or False in Python?

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.


2 Answers

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.

like image 147
chl Avatar answered Sep 23 '22 19:09

chl


Yes, it looks like this:

return i if i < x else x 

It's called the conditional operator in python.

like image 21
recursive Avatar answered Sep 22 '22 19:09

recursive