In Java, setting a variable to a value based on a condition could be done in one line like so:
variable = (!true) ? 1 : 2
This would result to '2'.
Is there python equivalent to this code?
Thank you.
In Java, setting a variable to a value based on a condition could be done in one line like so:
variable = (!true) ? 1 : 2
This would result to '2'.
Is there python equivalent to this code?
Thank you.
variable = 1 if not True else 2
General ternary syntax:
<value_if_true> if <condition> else <value_if_false>
This is called a conditional expression in Python, and is mostly equivalent to the "ternary operator" in C-family languages (although it's not actually an operator). The original proposal PEP 308 has more details.