Does Python have a ternary conditional operator? -
if python not have ternary conditional operator, possible simulate 1 using other language constructs?
yes, added in version 2.5.
syntax is:
a if condition else b
first condition
evaluated, either a
or b
returned based on boolean value of condition
if condition
evaluates true a
returned, else b
returned.
for example:
>>> 'true' if true else 'false' 'true' >>> 'true' if false else 'false' 'false'
keep in mind it's frowned upon pythonistas several reasons:
- the order of arguments different many other languages (such c, ruby, java, etc.), may lead bugs when people unfamiliar python's "surprising" behaviour use (they may reverse order).
- some find "unwieldy", since goes contrary normal flow of thought (thinking of condition first , effects).
- stylistic reasons.
if you're having trouble remembering order, remember if read out loud, (almost) mean. example, x = 4 if b > 8 else 9
read aloud x 4 if b greater 8 otherwise 9
.
official documentation:
Comments
Post a Comment