This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: "break" and "continue"-ing out of nested 'for' loops
Type: enhancement Stage:
Components: Interpreter Core Versions:
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: geraintluff, rhettinger
Priority: normal Keywords:

Created on 2005-05-29 22:59 by geraintluff, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg54545 - (view) Author: Geraint Luff (geraintluff) Date: 2005-05-29 22:59
I wasn't entirely sure whether this should go under
"Interpreter Core" or "Parser/Compiler", but whatever.

At the moment, "break" and "continue" can only break
out of the innermost "for" loop. I would appreciate a
way of breaking out of multiple 'for' or 'while' loops.

This would be extremely useful for instance when you
have some 'for' loops cycling through several
combinations, and you are using another 'for' loop to
check their validity (in my example, checking that my
two values are co-prime). In this situation, the only
solution I have found is to create a boolean variable
that is assigned a value when the check fails, just
before 'break'-ing out of a 'for' loop, and immediately
after that 'for' loop, having a statement that checks
the status of the boolean variable, and then
'continue's or 'breaks' again accordingly. I'm not an
experienced programmer, but this strikes me as
inefficient :p

Sorry if the above explanation is muddled. I can send a
short (15 lines) bit of code which might explain it better.

BTW, PHP seems to do this with "break 2;" or "continue
2;" which is very useful.

--G
msg54546 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2005-05-30 01:43
Logged In: YES 
user_id=80475

Sorry, this was considered and rejected long ago.  Most
other languages have made a similar choice.  In Python, the
best alternatives include:

* try/except which can penetrate multiple layers of looping
and/or function calls.

* boolean flags

* enclosing the innermost loops in a function so that a
return statement exits all pending loops within the function.

*and try/finally statements which are not a general purpose
replacement but do cover a whole class of use cases.

For more reading on the subject, take a look at Knuth's
Structured Programming with go to Statements.  That is a
rather thorough analysis of various structured constructs
and their strengths and weaknesses.
History
Date User Action Args
2022-04-11 14:56:11adminsetgithub: 42030
2005-05-29 22:59:22geraintluffcreate