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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -