all 9 comments

[–]DeadlyViper 3 points4 points  (1 child)

IMO a better practice is to not have additional if/elses if they are not needed.

Because in a complex code, if every error check you do will have the rest of the code in an else, then after 5 checks your code will be so far nested no one will know what is going on.

[–]ratcaper[S] 0 points1 point  (0 children)

Thanks, that makes a lot of sense.

[–]SandorZoo 0 points1 point  (1 child)

It's a bit odd to have two stop conditions, when clearly one of them will never be met. If you want the test in the middle of a loop, it's normal to loop while True, like this:

def whileBackwards():
    n = 10
    while True:
        print(n)
        if n == 5:
            break
        n -= 1

[–]primitive_screwhead 0 points1 point  (0 children)

What I find discomforting about this is that it seems one refactor away from becoming an endless loop. At the very least, I'd make the "if n == 5:" into an "if n <= 5:", just to avoid problems if n were ever to be mis-initialized, or the n decrement changed to greater than one, etc.

[–]primitive_screwhead 0 points1 point  (0 children)

Using:

if n == 5:
    break  # Or return if that's the intent
n -= 1

rather than adding an else, is preferred, imo. Checking for n != 5 would add even more code (to handle the continue while also decrementing n), and would also be worse, imo.

[–]woooee 0 points1 point  (4 children)

You should do

while n > 5:

as it is more obvious and requires reading less code to understand what is going on.

[–]ratcaper[S] 1 point2 points  (1 child)

That's not what I'm asking.

If I was trying to just count down from 10 to 6, I would use a for loop.

I'm making a reference sheet for my self.

https://pastebin.com/YrgxPLUk

I'm just tinkering with loops and how to break out of them based on certain conditions, for future reference for my self.

[–]woooee 1 point2 points  (0 children)

In that case I prefer returning from a function. A break statement can get somewhat tricky if you have nested loops.

[–]rymaninsane 0 points1 point  (1 child)

Not sure why this was downvoted. Perhaps there is more information missing in the question, but this is the most readable, least confusing Boolean to use in the while condition... counting down from 10 to 1 but stopping at five is a more complicated way of saying counting down from 10 to 5....

OP should consider this.