Python Forum
Good practices with Python if
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Good practices with Python if
#1
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 = ''
Reply
#2
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python: Regex is not good for re.search (AttributeError: 'NoneType' object has no att Melcu54 9 1,551 Jun-28-2023, 11:13 AM
Last Post: Melcu54
  Good Example for bi-directional Communication between Python and Windows (C#) raybowman 0 1,622 Nov-14-2020, 06:44 PM
Last Post: raybowman
  Best practices for searching lists of lists osxtra 1 1,546 Oct-24-2020, 07:34 PM
Last Post: Larz60+
  Would Python be a good langue to write this program in? MikeLG 4 3,973 Oct-02-2017, 09:51 PM
Last Post: nilamo
  Is the Python website good for learning Python? OnisionTheOninonBoy 18 11,371 Jan-30-2017, 09:21 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020