30

Possible Duplicate:
Ternary conditional operator in Python

I have this problem and have no idea to ask google for this:

(value == 'ok') ? 'ok' : 'not ok'

I mean that grammar with:

(expression) ? (return if <expresion> is true) : (return this value if <expresion> is false
Community
  • 1
  • 1
WBAR
  • 4,273
  • 6
  • 40
  • 77
  • 7
    As a note, this is called a 'ternary operator'. – Gareth Latty Oct 08 '12 at 20:24
  • In C, this is known as the "Ternary operator", Googling `python ternary operator` will point you where you want to go. – mgilson Oct 08 '12 at 20:25
  • Check out [this](http://stackoverflow.com/questions/394809/ternary-conditional-operator-in-python) question. Googling "Python ternary operator" brings you right to it. – Morrowind789 Oct 08 '12 at 20:26
  • 4
    I presume the downvote was from someone who thought this was a trivial answer to find, but it's actually quite hard to find if you don't know the term to look for. +1 – Gareth Latty Oct 08 '12 at 20:27
  • 1
    @mgilson as i wrote: I don't have idea how to ask google for it.. I didn't know the name of this grammar – WBAR Oct 08 '12 at 20:28
  • 1
    @WBAR --For what its worth, I'm with Lattyware, I don't agree with the downvote(s) either ... – mgilson Oct 08 '12 at 20:30
  • It may be more idiomatic for your method to return `True` or `False`. – Steven Rumbalski Oct 08 '12 at 20:31
  • I'm polish, so I don't know every english term.. I didn't know the name of it in my own language :) (always self learning programming languages via tutorials and reverse engineering) – WBAR Oct 08 '12 at 20:36
  • You may also want to return *something* or `None` if the *something* cannot be found. The `None` is the special object for such purpose. If the function ends with `return` without any argument, or if the function simply runs out of the body (no `return` command), it behaves to the caller as if `return None` was executed. – pepr Oct 08 '12 at 21:12
  • You could search for "python question mark operator" which gives the desired result. – phant0m Oct 09 '12 at 08:35

2 Answers2

37

Easy peasy:

'String ok' if value == 'ok' else 'String nok'

It's a conditional expression.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • 2
    Also masquerades as a ternary expression. – bossylobster Oct 08 '12 at 20:24
  • 19
    Although "conditional expression" is a much better name for it. Even in C "ternary operator" is a pretty stupid name; it's like calling `+` "binary operator". – Ben Oct 08 '12 at 20:33
11

How about this case:

{True: 'String ok', False: 'String nok'}[value == 'ok']

*Do not take seriously :)

defuz
  • 24,215
  • 8
  • 36
  • 59
  • 9
    This was similar to the old way of doing it before they added the `if else` syntax. But I used to see it with a tuple since a bool will eval to 0 or 1: `('NOT OK', 'OK')[value=="ok"] ` – jdi Oct 08 '12 at 20:55
  • @jdi that is still the prevalent practice in (gasp) *code golf* – Cyoce Mar 09 '16 at 08:19