Code on the same line

@PranavM , you will find that placing the if: on one line and the break on the next is generally acceptable and using a single line for even very simple compound statements is generally discouraged.

Readability is a fundamental principle in Python, so “generally” is a key word here.

  • If you are working with existing code, you will need to decide if following an established use of  
    if x == y: break   is clearer and “more readable” than applying the preferred style from PEP8. (Václav mentioned ‘breaking consistency’.)
  • Local project requirements could also require short if: statements to be single line (this level of detail in style requirements is rare but could happen).
  • a supervisor or manager could prefer or require short if: statements to be single line. It is probably best to use the manager’s style in this case–unless the code will be merged with other code that follows PEP8 as the general standard for that project.

Here is some of the “why” that you asked for:
PEP 8 also says that “it’s sometimes okay” but then shows the single-line style as “wrong”.

PEP8: While sometimes it’s okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements.
Rather not:…

# Wrong:
if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()
  • A very simple if: flows (reads) cleanly because there is no loop (but is still discouraged). It goes directly from   if A   to   then B   and ends immediately at   B.
  • The for: doesn’t flow very well as a single line because you have to stop and think for at least a fraction of a second about the looping.
  • The while doesn’t flow at all because it moves rapidly back and forth. This is mentally unpleasant.

With standards, it is usually simpler to say “Do it this way in all cases” instead of trying to add a bunch of exception cases. Otherwise some people will argue that a single-line for: is 100% okay.