Python Forum

Full Version: Good practices with Python if
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This kind of "if clause" works ok.

I'm just wondering if (no pun intended) this is good practice when writing Python.

sign = '-' if n < 0 else ''
Normally, I would start with "if", but the above is actually more human readable and succinct.

if n < 0:
    sign = '-'
else:
    sign = ''
It is excellent practice to use the conditional operator. It was introduced in Python 2.5, because people complained that Python lacked a ternary operator such as C's x = a ? b : c. Before that, people would sometimes use ersatz expressions such as
sign = ('', '-')[n < 0]