Python statement of short ‘if-else’

m = 100 if t == 0 else 5 # Requires Python version >= 2.5
m = (5, 100)[t == 0]     # Or [5, 7][t == 0]

Both of the above lines will result in the same thing.

The first line makes use of Python’s version of a “ternary operator” available since version 2.5, though the Python documentation refers to it as Conditional Expressions.

The second line is a little hack to provide inline functionality in many (all of the important) ways equivalent to ?: found in many other languages (such as C and C++).


Documentation of Python – 5.11. Conditional Expressions

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)