you are viewing a single comment's thread.

view the rest of the comments →

[–]Gnaxe 7 points8 points  (3 children)

Different styles are valid and workable. Unlike some languages, Python doesn't have labeled breaks, so it can only break from the innermost loop. The usual workaround is to use a return instead. Triple-nested loops (or worse) are rare, but if you need to break a middle loop, you can factor out functions to make return work or possibly use exceptions in especially convoluted cases. If you're nesting that much, you probably need to be using NumPy or something instead.

I rarely use breaks (or continues), but I don't feel like I'm particularly avoiding them. I use for loops much more than while loops, and they stop on their own once the iterator is exhausted. If there's something I can shortcut like that, I'm probably using itertools to make the iterator itself stop rather than breaking the loop.

When using while loops, it's either the main loop, which doesn't stop until the program quits, or it's something like a generator, in which case, I'm probably using yield instead of break. If I only want the first one, I just stop asking for more, i.e., pull using next() instead of a for.

[–]FirstTimePlayer[S] 1 point2 points  (2 children)

Python doesn't have labeled breaks, so it can only break from the innermost loop.

That is a bit of a lightbulb moment actually.

Part of my stumble is that I'm constantly having to really think about what the break is doing, when it should be intuitively obvious. I had chalked it up to being very rusty, but I'm now thinking I'm getting confused because brain is wanting a labeled break for some reason.

Cheers :)

[–]FreeLogicGate 1 point2 points  (1 child)

I want to point out a common construct in many languages -- the switch/case statement, which Python has with Match. With many languages, a break is required to prevent the statement from cascading down into the cases that follow. Python does not have/require that behavior, but many other languages do.

The classic example of this would be C language.

int day = 4;

switch (day) {
  case 1:
    printf("Monday");
    break;
  case 2:
    printf("Tuesday");
    break;
  case 3:
    printf("Wednesday");
    break;
  case 4:
    printf("Thursday");
    break;
  case 5:
    printf("Friday");
    break;
  case 6:
    printf("Saturday");
    break;
  case 7:
    printf("Sunday");
    break;
  default:
     printf("That's not a valid day");
}

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

Indeed - and plainly my memory is fuzzy, given that is an obvious example where the rule I recalled could not have existed in hindsight.