0

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.

TheProofIsTrivium
  • 768
  • 2
  • 11
  • 25
  • For future reference, this is known as the ternary operator. That term should be much more search-friendly than "inline if". – user2357112 Aug 02 '13 at 01:26
  • Given that `!true` is a constant, the easiest way to write this in one line is `variable = 2`. :) – abarnert Aug 02 '13 at 01:33
  • 1
    @user2357112: Actually, in Python, it's called a "conditional expression", and `if` is explicitly _not_ an operator. However, after a bit of resistance, they relented and added `sometimes called a "ternary operator"` to [the docs](http://docs.python.org/3/reference/expressions.html#conditional-expressions) because that's what everyone coming from C-family languages searches for. – abarnert Aug 02 '13 at 01:36
  • @abarnert That was just an example. The conditional in there can be anything. – TheProofIsTrivium Aug 02 '13 at 04:47
  • @Yoni201: I was pretty sure of that, which is why I put it as a comment (with a stupid smiley) rather than an answer. – abarnert Aug 02 '13 at 18:17

1 Answers1

5
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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
mshsayem
  • 17,557
  • 11
  • 61
  • 69