why only one ":" in a line ... ?

Andreas Leitgeb Andreas.Leitgeb at siemens.at
Mon Aug 19 17:06:08 CEST 2002

Being relatively new to python, there are some things I'd simply need 
to get used to.  But this becomes easier, if I understand it's 
background, therefore this question:

Why can't I squeeze certain constructs in a single line ?

 I don't want to discuss the worth of putting something in one line,
 what I could also break up into more lines. It's just that for
 some blocks, I as a programmer would prefer them in one line.

 if 0<n<10: for i in range(n): print i
this is invalid.
but why is it invalid ?

One could argue, that if next line startet with "else", then the compiler
couldn't tell if the "else" belonged to "for" or "if", and I would 
understand, because this construct would be ambiguous: 
  if 0<n<10: for i in range(n): print i
  else: print n

Also, if next line is indented (and nothing is after the last colon of
the first line), then it would be ambiguous, too:
  if 0<n<10: for i in range(n):
     print i   # <-- is that supposed to be inside if or for ?
(even though it could be canonically disambiguou'ified.)

But if next line starts at same level as the previous line, and it does
not start with "else":  ?
  if 0<n<10: for i in range(n): print i
  print n
Nothing ambiguous here, imho.
So what's so bad about "putting stuff in one line" ?

My motivation for this question:
During porting some old c-code, that contained lots of simple blocks like:
  while (cond1) { stmt; if (cond2) break; }
these lines were simple enough, that their one-lined'ness did not
obfuscate it, but rather made it more readable.

In Python however, each of these phrases need to get expanded to  
  *three* lines, because even the small "stmt" needs it's own line!
  (I can't put it after the "while" nor in front of the "if")

In this group some of you have done good jobs already, enlightening me
to pythonian ways of thinking, so I look forward to getting enlightened 
on this one, too :-)

More information about the Python-list mailing list