Python Forum
Good practices with Python if - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Good practices with Python if (/thread-35470.html)



Good practices with Python if - Pedroski55 - Nov-06-2021

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 = ''



RE: Good practices with Python if - Gribouillis - Nov-07-2021

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]