• AMillionMonkeys@lemmy.world
    link
    fedilink
    English
    arrow-up
    10
    ·
    9 months ago

    One of these days I’ll read through the PEP and figure out why Python doesn’t have do-while. I understand that it’s just as bad, but while(True) feels so dangerous.

    • DreamButt@lemmy.world
      link
      fedilink
      English
      arrow-up
      5
      ·
      9 months ago

      Curious what use case you have for needing a do-while. Honestly I barely use while at all, a good ol for-loop normally does the trick

      • pixelscript@lemmy.ml
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        9 months ago

        I got an application that runs through a big calculation that has to pass several sanity checks along the way. If any check fails, the input parameters are tweaked and the calculation starts again from the top, iteratively approaching the ideal solution. Do-while is perfect for this.

        It beats recursion in non-tail-call-optimized implementations (JavaScript…). And while this could be done just as well with a comon while loop plus a flag variable, I like the way the syntax of do-while naturally reads as, “Do [thing]. … Did it work? No? Do it again”.

        I’d still argue it’s redundant. If they got rid of it tomorrow I’d refactor and cope with no complaints. But as long as it’s around, I like using it.

      • prograhammingdev@lemmy.prograhamming.com
        link
        fedilink
        arrow-up
        1
        ·
        9 months ago

        IMO I find it really useful in scenarios where you have a set condition that needs to be met (and can always be met so it’s not endless) and looping through to achieve it. I wrote a simple part calculation for a production company I worked for. Essentially while parts_needed < parts packed, pack qty 'x' of part 1, and qty 'x' of part 2 until all parts were filled to the correct amounts. Though it can be done with either / both I just find it more legible.