473,796 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 7923
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.

# DeprecationWarn ing: raising a string exception is deprecated

def Goto_is_not_dea d(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_dea d(2)
Goto_is_not_dea d(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

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

Similar topics

226
12718
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}
20
3862
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...
28
3309
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...
41
3559
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.
2
4455
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>
150
6589
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
13
2161
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
8377
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...
0
946
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
0
10459
Oralloy
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...
1
10187
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,...
0
10018
tracyyun
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...
0
9055
agi2029
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...
0
6795
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5446
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...
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.