Good python equivalent to C goto

Matthew Fitzgibbons elessar at nienna.org
Sun Aug 17 14:09:23 EDT 2008


Kurien Mathew wrote:
> Hello,
> 
> Any suggestions on a good python equivalent for the following C code:
> 
> while (loopCondition)
> {
>     if (condition1)
>         goto next;
>     if (condition2)
>         goto next;
>     if (condition3)
>         goto next;
>     stmt1;
>     stmt2;
> next:
>     stmt3;
>     stmt4;
>  }
> 
> 
> 
> Thanks
> Kurien
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I would not be too happy if I saw C code like that in my repository. 
This is equivalent:

while (loopCondition) {
     if (!(condition1 || condition2 || condition3)) {
         stmt1;
         stmt2;
     }
     stmt3;
     stmt4;
}


In Python:

while (loopCondition):
     if not (condition1 or condition2 or condition3):
         stmt1
         stmt2
     stmt3
     stmt4

If stmt3 and stmt4 are error cleanup code, I would use try/finally.

while loopCondition:
     try:
         if condition1:
             raise Error1()
         if condition2:
             raise Error2()
         if condition3:
             raise Error3()
         stmt1
         stmt2
     finally:
         stmt3
         stmt4

This will also bail out of the loop on and exception and the exception 
will get to the next level. If you don't want that to happen, put an 
appropriate except block before the finally.

-Matt



More information about the Python-list mailing list