0

Is there python function in standard library like

def cond(condition, true, false):
  if condition:
    return true
  return false

x = 20
s = cond(x > 10, "x greater than 10", "x less or equals 10")
atomAltera
  • 1,702
  • 2
  • 19
  • 38
  • 1
    Related question [Python Ternary Operator](http://stackoverflow.com/questions/394809/python-ternary-operator). – RanRag May 07 '12 at 20:47
  • 1
    Such a function shouldn't exist, since it will evaluate both true and false arguments in all cases. – kindall May 07 '12 at 20:57

2 Answers2

9

Python has a ternary operation but it is done as an "if expression" instead of with question mark and colon.

s = "x greater than 10" if x > 10 else "x less or equals 10"
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
wberry
  • 18,519
  • 8
  • 53
  • 85
2

Python has a ternary-like operator (it's actually called a conditional expression), which reads like this:

s = "x greater than 10" if x > 10 else "x less or equals 10"
Makoto
  • 104,088
  • 27
  • 192
  • 230