"Goto" statement in Python

Chris Angelico rosuav at gmail.com
Thu Apr 13 10:35:20 EDT 2017

On Thu, Apr 13, 2017 at 9:31 PM, alister <alister.ware at ntlworld.com> wrote:
> I expect you could simulate most of these with a custom exception
> for example break from nested loop:
> class GoTo(Exception):
>     pass
> try:
>     for i in range(100):
>         print i
>         for j in range (50):
>             print j
>             if i*j>60:
>                 raise GoTo
> except GoTo:
>     print "Exit Early"
> print "end of loop"

Or you could turn it into a function and "return". Or if you feel like
it, you could turn the nested loops into a generator, then iterate
over it and break when you need to. There are many things you CAN do,
but to the true goto-aficionado, none of them is as clean.

Personally, I can't remember the last time I yearned for "goto" in
Python, and the only times I've ever wished for it or used it in other
languages have been multi-loop breaks or "for...else" blocks. And
neither is very frequent.


More information about the Python-list mailing list