In the Absence of a GoTo Statement: Newbie needs menu-launcher to choose amongst sub-programs

Steve Holden sholden at holdenweb.com
Fri Apr 13 14:55:11 EDT 2001


"Ron Stephens" <rdsteph at earthlink.net> wrote in message
news:3AD5EEEF.C4CB8AF2 at earthlink.net...
> Sacrilege, I know. ;-))) But sometimesIi wonder why no modern language
> will let me have a simple goto statement when nothing else will do as
> well...this is a rhetorical statement only...
>
[attempted GOTO justification considered harmful ... :-]
>
> So, now  I consider procedural menu program using raw_input. Still, how
> do I go to the appropriate sub-program when the user chooses one? With
> goto's this would be trivial. Now, I consider a nested set of "if "
> statements that determines which number was chosen, but still how do I
> "jump" to the correct sub-program???

choice = raw_input("Option: ")
if choice == 1:
    # code for case 1
elif choice == 2:
    # code for case 2
elif choice == 3:
    :
    :
else:
    print "Invalid choice"

                                                            Even if I define
the subprograms as
> functions even, how do I jump to them???

One way woud be ...

def choice1():
    :
    :
def choice2()
    :
    :
choices = [choice1, choice2, ... ]

choice = raw_input("Option: ")
choices[int(choice)]

> Any help for hopelessly confused newbie will be greatly appreciated...
>
I would only add that if you think your programming language *needs* a goto
statement then you might look into the history of something called
"structured programming". Basically, goto statements are dangerous -- in the
wrong hands -- because they allow almost random sequences of control inside
a program. It's not that using goto necessarily turns your programs into
spaghetti, simply that it will if not used with proper discipline. Very few
new programmers exerted the proper discipline!

If a program executes using only sequences of instructions, choices and
loops. it's easier to see what it does and how it works, and easier, too, to
reason about its performance (even to oneself, while debugging, for
example).

I myself converted to structured programming in the early 1980's, after
about twelve years programming in Algol, assembler, Fortran, etc. It was a
painful experience for a month or so, but once you get used to it you'll not
want a goto statement back, I assure you!

Good luck

regards
 Steve






More information about the Python-list mailing list