Replace for Goto

John Pote john at jptechnical.demon.co.uk
Thu May 29 18:55:43 EDT 2003


Some interesting replies on this topic. Despite protests from many
fellow programmers I still think the GOTO can be used appropriately,
though not very often - spaghetti logic is bad/hard/bug ridden to debug
and impossible to maintain. The main use to my mind is in a part of a
program that models a state machine. Finite State Machines are widely
used in many embedded control systems (my own area) because they model
how external events cause changes in the system. All states are at the
same structural 'level' in the program, they are not subroutines. In a
state called 'motor off' an event (operator presses button) causes the
FSM to perform an action (turn on the motor) and then move to the next
state, for example 'motor on'. This change of state is semantically a
goto. In this case a goto statement exactly fits the real world object
the program is modelling. My thinking remains the same whether it is the
real system  or the program that I am thinking about.

That said it is quite easy to construct a framework using a loop with a
state variable representing the current state and ifs or a dictionary to
call subroutines implementing each state, only a little overhead has
been added. This approach also means that at the end of each pass
through the state machine the program can 'do' something else before
looping back for another pass through the state machine.

John Pote



>Dvm5 fed this fish to the penguins on Wednesday 28 May 2003 05:46 pm:
>
>> I'm used to Basic. There is a Goto/Label command, you put goto where
>> you want it to come from and label where you want it to go. Simple.
>> How can I do this in Python?
>
>        <shudder>
>
>        Not even "geewhiz" BASIC (IE, variants of the M$ BASIC on the late 
>TRS-80s and the second BASIC on the Amiga) required one to code using 
>GOTO... And those are over a decade old.
>
>        "Structured Programming" (which precedes the current craze for "Object 
>Oriented") relies on the concept that any structure has one way in, and 
>one way out. You can have branches inside, but each branch also has one 
>way in, one way out.
>> 
>> What I'm trying to do is create a "play again" type user interface.
>> Thus, I can't alter the program to use an If command; the option has
>> to be at the end, and the effect has to be at the begining! How do I
>> accomplish this?
>> 
>
>while 1:        #infinite loop
>        #do the main stuff in the program
>        ans = raw_input("Play again? (y/n)")
>        if ans == "n":
>                break
>
>
>





More information about the Python-list mailing list