How to avoid "flags"?
I read that utilizing flags is deprecated in modern programming. Can someone explain me how to avoid it when I want to go out of multiple "for" loops?
I read that utilizing flags is deprecated in modern programming. Can someone explain me how to avoid it when I want to go out of multiple "for" loops?
Asked: 6 years ago
Seen: 834 times
Last updated: Nov 26 '18
If I use a single "break" instruction, I come out of a single loop, and, for example, I need to go out of all of them.
What do you mean by "flags" or "modern programming"? It depends on the exact logic, but in Python usually some boolean flag is the best way to break out of nested loops. Raising some exception can be another way.
I mean, if we consider this example, when the flag goes to zero, I would go directly to next n, without the program having to try all other p,q,r, something like the od "goto":
How would you write such a program (possibly also with rising exception, which I don't know)?
The "best" solution to dealing with deeply nested loops like this is often going to depend on the particular problem at hand. In this case you might write this as a specialized iterator and then loop over the combinations with a single for loop. Fortunately, this particular iterator has alread been written and you can do this like:
This way avoids lot of duplicate work as well, since it avoids recalculating
prime_range([x > 2], N)
so many times.See https://docs.python.org/2/library/ite...