Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

Same here, I often find myself writing a loop-and-a-half and will on occasion repeat expressions to get around extra lines (if I cared about performance, I wouldn't be writing it in Python).

I feel like a lot of the resistance is from people who think this is somehow bad style, because it's associated with a source of bugs in other languages. The same kind of people will argue endlessly against having 'goto' in a language, even when it can clearly make for cleaner code (eat it, Dijkstra!) in some cases.



I think EWD was basically in the right to push hard for structured programming, but I also like Knuth's nuanced take:

https://pic.plover.com/knuth-GOTO.pdf


Can you explain what a "loop-and-a-half" is in Python?


    x = stuff
    while x:
        x = stuff


On the contrary, loop-and-a-half is intended to avoid repeating stuff outside and inside of the loop body.

    while true:
        x = stuff
        if not x:
            break


GPs example is perfectly valid as well - this is just a restatement of the same logic in a way that keeps the logic contained within the loop at the cost of using a conditional plus a break inside of an unconditional loop. See [0]:

  Another motivating code pattern is the "loop and a half".
 
  It was once common for processing a file by line, but that 
  has been solved by making file objects iterable; however 
  other non-iterable interfaces still suffer from patterns 
  like:
  
  line = f.readline()
  while line:
      ...  # process line
      line = f.readline()
  
  or like this:
  
  while True:
      line = f.readline()
      if not line:
          break
      ... # process line

  Either of those could be replaced with a much more clear
  and concise version using an assignment expression:

  while line := f.readline():
      ... # process line
[0]: https://lwn.net/Articles/757713/




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: