473,378 Members | 1,209 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Good python equivalent to C goto

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
Aug 16 '08 #1
22 7876
Kurien Mathew schrieb:
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;
}
while loopCondition:
if not( cond1 or cond2 or cond3 ):
stmt1
stmt2
stmt3
stmt4

Not tested.
Greetings,
Thomas

--
Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison!
(Coluche)
Aug 16 '08 #2
Kurien Mathew wrote:
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;
}
seems as if you *don't* want to execute the first part if any of the
conditions are true. in other words,

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

</F>

Aug 16 '08 #3
Kurien Mathew wrote:
Hello,

Any suggestions on a good python equivalent for the following C code:
There are various ways to write your example in Python. For example

while loopCondition:
condition = 1
while condition:
if condition1:
break
if condition2:
break
if condition3:
break
stmt1
stmt2
condition = 0
else:
stmt3
stmt4

The else block of while isn't execute if you break out of while.

You can emulate multiple gotos with exceptions. In general you shouldn't
try to mimic C in Python code. C like Python code is often hard to read
and slower than well designed Python code.

Aug 16 '08 #4
Dennis Lee Bieber wrote:
Nasty code even for C... I've never used goto in C... Options:
convert the statements of next into a function, and put in an else
clause...
I think the parent post's pseudocode example was too simple to show the
real benefits and use cases of goto in C. Obviously his simple example
was contrived and could easily be solved with proper if tests. Your
idea of using a function is correct for python, though, but not for C

However, what you say about else clauses gets extremely hairy when you
have to deal with multiple nested if statements. The most common use
case in C for goto is when you have cleanup code that must run before
leaving a function. Since any number of things could happen while
processing a function (at any level of the if statement) that would
trigger an exit, having a whole bunch of else statements gets very, very
tedious and messy. Often involves a lot of code duplication too. Goto
is direct and much cleaner and more readable.

A function in C wouldn't work for this because of scoping rules.

However it's not necessary in python to do any of this, since you can
define nested functions that have access to the parent scope. Anytime
you need to clean up, just call the nested cleanup function and then return.
Aug 17 '08 #5
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;
}
I think the most direct translation would be this:

def whateverfunc():

def next_func():
stmt3
stmt4

while loopCondition:
if condition1:
next_func()
return
if condition2:
next_func()
return
if condition3:
next_func()
return
stmt1
stmt2


Aug 17 '08 #6
Michael Torrie wrote:
I think the most direct translation would be this:
Nevermind I forgot about the while loop and continuing on after it.
Guess the function doesn't quite fit this use case after all.
Aug 17 '08 #7
On Aug 17, 12:35*am, Michael Torrie <torr...@gmail.comwrote:
However it's not necessary in python to do any of this, since you can
define nested functions that have access to the parent scope. *Anytime
you need to clean up, just call the nested cleanup function and then return.
That is unnecessary and dangerous in Python.

98% of the time the Python interpreter cleans up what you would have
had to clean up by hand in C.

The rest of the time you should be using a try...finally block to
guarantee cleanup, or a with block to get the interpreter do it for
you.

Calling a nested function to perform cleanup is prone to omission
errors, and it doesn't guarantee that cleanup will happen if an
exception is raised.
Carl Banks
Aug 17 '08 #8
as an oldtimer, I know that in complex code the goto statement is
still the easiest to code and understand.

I propose this solution using exception.

The string exception is deprecated but is simpler for this example.

# DeprecationWarning: raising a string exception is deprecated

def Goto_is_not_dead(nIn):
try:
if (nIn == 1): raise 'Goto_Exit'
if (nIn == 2): raise 'Goto_Exit'

print 'Good Input ' + str(nIn)
raise 'Goto_Exit'

except 'Goto_Exit':
print 'any input ' + str(nIn)

if __name__ == '__main__':
Goto_is_not_dead(2)
Goto_is_not_dead(3)
Aug 17 '08 #9
On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew wrote:
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;
}
(Don't) use the `goto` module: http://entrian.com/goto/ :-)

from goto import goto, label

# ...

while loop_condition:
if condition1 or condition2 or condition3:
goto .next
print 'stmt1'
print 'stmt2'
label .next
print 'stmt3'
print 'stmt4'
Ciao,
Marc 'BlackJack' Rintsch
Aug 17 '08 #10
On 2008-08-16, Dennis Lee Bieber <wl*****@ix.netcom.comwrote:
On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew <km*****@envivio.fr>
declaimed the following in comp.lang.python:
>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;
}

Nasty code even for C... I've never used goto in C...
I do sometimes, but it's for exception handling, and in Python
one uses try/raise/except. The example above isn't the best
way to show this, but perhaps something like the code below

while loopCondition:
try:
if condition 1:
raise MyException
if condition 2:
raise MyException
if condition 3:
raise MyException
stmt1;
stmt2;
stmt3;
except: MyException
pass
stmt4;
stmt5;

--
Grant Edwards grante Yow! People humiliating
at a salami!
visi.com
Aug 17 '08 #11
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
Aug 17 '08 #12
On Aug 17, 8:09*pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
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 -
class Goto_Target(Exception):
pass

def Goto_is_not_dead(nIn):
try:
if (nIn == 1): raise Goto_Target
if (nIn == 2): raise Goto_Target

inv = 1.0 / nIn
print 'Good Input ' + str(nIn) + ' inv=' + str(inv)

except Goto_Target:
pass
except Exception, e:
print 'Error Input ' + str(nIn) + ' ' + str(e)
finally:
print 'any input ' + str(nIn)

if __name__ == '__main__':
Goto_is_not_dead(0)
Goto_is_not_dead(2)
Goto_is_not_dead(3)
Aug 17 '08 #13
in**@orlans-amo.be wrote:
On Aug 17, 8:09 pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
>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 -

class Goto_Target(Exception):
pass

def Goto_is_not_dead(nIn):
try:
if (nIn == 1): raise Goto_Target
if (nIn == 2): raise Goto_Target

inv = 1.0 / nIn
print 'Good Input ' + str(nIn) + ' inv=' + str(inv)

except Goto_Target:
pass
except Exception, e:
print 'Error Input ' + str(nIn) + ' ' + str(e)
finally:
print 'any input ' + str(nIn)

if __name__ == '__main__':
Goto_is_not_dead(0)
Goto_is_not_dead(2)
Goto_is_not_dead(3)
--
http://mail.python.org/mailman/listinfo/python-list
I think this is needlessly ugly. You can accomplish the same with a
simple if-else. In this case you're also masking exceptions other than
Goto_Target, which makes debugging _really_ difficult. If you need to
have the cleanup code executed on _any_ exception, you can still use
try-finally without any except blocks. Your code is equivalent to this:

def goto_is_dead(n):
try:
if n == 0 or n == 1 or n == 2:
# if you're validating input, validate the input
print "Error Input %s" % n
else:
print "Good Input %s inv= %s" % (n, (1. / n))
finally:
print "any input %s" % n

if __name__ == '__main__':
goto_id_dead(0)
goto_id_dead(2)
goto_id_dead(3)

More concise, readable, and maintainable.

-Matt
Aug 17 '08 #14
On Aug 16, 11:20*pm, Kurien Mathew <kmat...@envivio.frwrote:
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;
* }
Extract complex test as a function. Assuming conditions 1, 2 and 3 are
difficult enough not to put them all one one line, put them in a
function which describes what they're testing.

def should_do_12(args):
if condition1:
return False
if condition2:
return False
if condition3:
return False
return True

while loop_condition:
if should_do_12(args):
stmt1
stmt2
stmt3
stmt4

This is probably the right way to write it in C too.

--
Paul Hankin
Aug 17 '08 #15
On Aug 17, 9:23*pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
i...@orlans-amo.be wrote:
On Aug 17, 8:09 pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
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 -
class Goto_Target(Exception):
* * pass
def Goto_is_not_dead(nIn):
* * try:
* * * * if (nIn == 1): raise Goto_Target
* * * * if (nIn == 2): raise Goto_Target
* * * * inv = 1.0 / nIn
* * * * print 'Good Input ' + str(nIn) + ' inv=' + str(inv)
* * except Goto_Target:
* * * * pass
* * except Exception, e:
* * * * print 'Error Input ' + str(nIn) + ' ' + str(e)
* * finally:
* * * * print 'any input ' + str(nIn)
if __name__ == '__main__':
* * Goto_is_not_dead(0)
* * Goto_is_not_dead(2)
* * Goto_is_not_dead(3)
--
http://mail.python.org/mailman/listinfo/python-list

I think this is needlessly ugly. You can accomplish the same with a
simple if-else. In this case you're also masking exceptions other than
Goto_Target, which makes debugging _really_ difficult. If you need to
have the cleanup code executed on _any_ exception, you can still use
try-finally without any except blocks. Your code is equivalent to this:

def goto_is_dead(n):
* * *try:
* * * * *if n == 0 or n == 1 or n == 2:
* * * * * * *# if you're validating input, validate the input
* * * * * * *print "Error Input %s" % n
* * * * *else:
* * * * * * *print "Good Input %s inv= %s" % (n, (1. / n))
* * *finally:
* * * * *print "any input %s" % n

if __name__ == '__main__':
* * *goto_id_dead(0)
* * *goto_id_dead(2)
* * *goto_id_dead(3)

More concise, readable, and maintainable.

-Matt- Hide quoted text -

- Show quoted text -
as mentioned 'in complex code the goto statement is still the easiest
to code and understand'.
The examples are very small and do not require that at all. I agree
it's ugly.
Just to show a way to do it.

A very few functions where I use goto in C or C# are a few hundred
lines of code, difficult to split in smaller functions.
A lot of common data.
One coming to my mind is a complex validation function for the user
input of a complex transaction.
If any test fails, goto the cleaning part and issue error message.

The goto code is the simpler way to do it.
We are not talking about simple if-else, but let say 20 if-else.
Many nested if-else are more difficult to understand and do not fit
better the semantics.
Aug 17 '08 #16
in**@orlans-amo.be wrote:
The goto code is the simpler way to do it.
We are not talking about simple if-else, but let say 20 if-else.
Many nested if-else are more difficult to understand and do not fit
better the semantics.
let's see...

$ cd ~/svn/python25
$ grep goto */*.c | wc
2107 7038 86791

but given that the Python language doesn't have a goto statement, can we
perhaps drop this subtopic now?

</F>

Aug 17 '08 #17
as mentioned 'in complex code the goto statement is still the easiest
to code and understand'.
The examples are very small and do not require that at all. I agree
it's ugly.
Just to show a way to do it.

A very few functions where I use goto in C or C# are a few hundred
lines of code, difficult to split in smaller functions.
A lot of common data.
One coming to my mind is a complex validation function for the user
input of a complex transaction.
If any test fails, goto the cleaning part and issue error message.

The goto code is the simpler way to do it.
We are not talking about simple if-else, but let say 20 if-else.
Many nested if-else are more difficult to understand and do not fit
better the semantics.
--
http://mail.python.org/mailman/listinfo/python-list
I'm sorry, but if you have any single function that's a few hundred
lines of code, you need to do some serious refactoring. How do you even
begin to test that? A goto is just a hack that hides underlying
problems. If I see a function of more than about twenty lines or having
more than two or three execution paths, I start thinking of ways to
break it down.

There are a lot of approaches. Paul Hankin put all the conditionals in a
helper function. Similarly, you could do something like this (for more
fun make the validators pluggable):

# each validator is a function that takes the input the be validated
# and returns True for good input; otherwise False
_foo_validators = [_check_this, _check_that, _check_the_other] # etc.

def foo(input):
for v in _validators:
if not v(input):
_on_bad_input(input)
break
else:
_on_good_input(input)
_on_all_input(input)

Alternatively, you can often turn complex input validation into a state
machine.

-Matt
Aug 18 '08 #18
On Sun, 17 Aug 2008 09:08:35 -0500, Grant Edwards wrote:
In Python one uses try/raise/except.
At the risk of introducing an anachronism and in deference to
Mr. "ElementTree" Lundh, I now invoke Godwin's Law (1990):

Isn't *try/except* kinda sorta like the musty, old *come from*
construct proposed for *fortran*?

Here there be typos (abject apologies):

o Clark, R. Lawrence. "A Linguistic Contribution to GOTO-less
Programming." _Datamation_ Dec. 1973. 18 Aug. 2008
<http://www.fortranlib.com/gotoless.htm>.

--
... Be Seeing You,
... Chuck Rhode, Sheboygan, WI, USA
... Weather: http://LacusVeris.com/WX
... 71° — Wind W 9 mph
Aug 18 '08 #19
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;
}
such a pity that the goto module

http://mail.python.org/pipermail/pyt...il/002982.html

never got into core python :)
--
Robin Becker

Aug 18 '08 #20

-----Original Message-----
From: py********************************@python.org [mailto:python-
li*************************@python.org] On Behalf Of Kurien Mathew
Sent: Saturday, August 16, 2008 5:21 PM
To: py*********@python.org
Subject: Good python equivalent to C goto

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;
}

===========================
Use a flag and a one loop for loop
while loopCondition:
flag = False
for i in range(1):
if condition1:
break
if condition2:
break
if condition3:
break
stmt1
stmt2
flag = True
if not flag:
stmt3
stmt4
===========================
Or just a straight flag

while ( loopCondition ):
flag = False

if (condition1)
flag = True # goto next;
if (not flag and condition2)
flag = True # goto next;
if (not flag and condition3)
flag = True # goto next;

if not flag:
stmt1
stmt2
else
stmt3
stmt4

*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622
Aug 18 '08 #21
On Aug 17, 1:09*pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
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
Aug 18 '08 #22
Paul McGuire wrote:
On Aug 17, 1:09 pm, Matthew Fitzgibbons <eles...@nienna.orgwrote:
>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
I'm aware my example where I raised exceptions was functionally
different ("This will bail out of the loop on an exception and the
exception will get to the next level.") Just thinking in terms of
telling the caller something went wrong. The other examples were
functionally equivalent, however.

Still, this is the best way so far. :) I never thought of using continue
with finally. It gets added to my Python tricks file for future use.

-Matt
Aug 18 '08 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

226
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type...
20
by: BJ MacNevin | last post by:
Hi all, I teach middle school and am currently trying to bring some computer science to the students. Our district has a wonderfully linked network throughout all our schools... done via MS...
28
by: David MacQuigg | last post by:
I'm concerned that with all the focus on obj$func binding, &closures, and other not-so-pretty details of Prothon, that we are missing what is really good - the simplification of classes. There are...
41
by: Xah Lee | last post by:
here's another interesting algorithmic exercise, again from part of a larger program in the previous series. Here's the original Perl documentation: =pod merge($pairings) takes a list of...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
150
by: tony | last post by:
If you have any PHP scripts which will not work in the current releases due to breaks in backwards compatibility then take a look at http://www.tonymarston.net/php-mysql/bc-is-everything.html and...
13
by: Steven Bethard | last post by:
Jean-Paul Calderone <exarkun@divmod.comwrote: Interesting. Could you give a few illustrations of this? (I didn't run into the same problem at all, so I'm curious.) Steve
206
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a...
0
by: Jean-Paul Calderone | last post by:
On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew <kmathew@envivio.frwrote: Goto isn't providing much value over `if´ in this example. Python has a pretty serviceable `if´ too: while...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.