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
22 7928
On 2008-08-16, Dennis Lee Bieber <wl*****@ix.net com.comwrote:
On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew <km*****@envivi o.fr>
declaimed the following in comp.lang.pytho n:
>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
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
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(Exc eption):
pass
def Goto_is_not_dea d(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_dea d(0)
Goto_is_not_dea d(2)
Goto_is_not_dea d(3) 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(Exc eption):
pass
def Goto_is_not_dea d(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_dea d(0)
Goto_is_not_dea d(2)
Goto_is_not_dea d(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
On Aug 16, 11:20*pm, Kurien Mathew <kmat...@envivi o.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(ar gs):
if condition1:
return False
if condition2:
return False
if condition3:
return False
return True
while loop_condition:
if should_do_12(ar gs):
stmt1
stmt2
stmt3
stmt4
This is probably the right way to write it in C too.
--
Paul Hankin
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(Exc eption):
* * pass
def Goto_is_not_dea d(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_dea d(0)
* * Goto_is_not_dea d(2)
* * Goto_is_not_dea d(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. 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>
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_othe r] # etc.
def foo(input):
for v in _validators:
if not v(input):
_on_bad_input(i nput)
break
else:
_on_good_input( input)
_on_all_input(i nput)
Alternatively, you can often turn complex input validation into a state
machine.
-Matt
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. "ElementTre e" 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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 "help", "copyright", "credits" or "license" for more information.
>>> d1 = {'a':1}
>>> d2 = {'b':2}
>>> d3 = {'c':3}
|
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 Windows Network. In order to protect the
network, our district's IT department does not want things installed on the
system (or at least makes it VERY difficult to get it done). SO, I am using
MSW Logo installed onto a CD-ROM... we just stick in the...
|
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 a number of
aspects to this simplification, but for me the unification of methods
and functions is the biggest benefit.
All methods look like functions (which students already understand).
Prototypes (classes) look like modules. This will...
|
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 pairs, each pair indicates the
sameness
of the two indexes. Returns a partitioned list of same indexes.
|
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 */
#include <time.h>
| |
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 see if
you agree with my opinion or not.
Tony Marston
http://www.tonymarston.net
|
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
|
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 footprint which says:
"Indeed, one often hears arguments against building exibility into an
engineered sys-
tem. For example, in the philosophy of the computer language Python it
is claimed:
\There should be one|and preferably only one|obvious...
|
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 loopCondition:
if not (condition1 or condition2 or condition3):
stmt1
stmt2
stmt3
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |