Kategori : Python02 Mei 2018 10:00:46

Python Ternary Operator

Python ternary operator introduced in Python 2.5.

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

[expression] and [on_true] or [on_false]

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

source : https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

Share : Share Facebook Share Twitter
Kategori : Python02 Mei 2018 10:00:46

zuka.one
©2011