On Aug 17, 1:09 pm, Matthew Fitzgibbons <[EMAIL PROTECTED]> wrote: > 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- Hide quoted text - > > - Show quoted text -
Close, but there is no reason for the conditions to raise anything, they can just use the continue statement: i = 20 while i > 0: try: if i % 2: continue if i % 3: continue print i, "is even and a multiple of 3" finally: i -= 1 Prints: 18 is even and a multiple of 3 12 is even and a multiple of 3 6 is even and a multiple of 3 I think this is closest to the OP's stated requirements. -- Paul -- http://mail.python.org/mailman/listinfo/python-list