# 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?

Please start posting anonymously - your entry will be published after you log in or create a new account.

Asked: ** 2018-11-26 10:58:46 +0200 **

Seen: **383 times**

Last updated: **Nov 26 '18**

Porting a finite-differences-matrix from Matlab to Numpy

Way to make default output numerical not symbolic?

Generation of all 3-index tensors with {-1,0,1} as entries.

How to create a loop with two variables?

Trying to print and plot two parameters of multivariate functions

How can I get Sage to go over all possible maps between two sets?

Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.

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...