In the Absence of a GoTo Statement: Newbie needs menu-launcher to choose amongst sub-programs
Alex Martelli
aleaxit at yahoo.com
Fri Apr 13 15:00:58 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...
Answering rhetorical questions is one of my favorite hobbies, and,
here, the answer is: "because, in a well-designed language, there
is no situation in which ``nothing else will do as well''":-).
> I have written and am writing a series of similar small programs to help
> a user choose amongst several different alternatives. The programs
...
> user can choose the general program, or else a specific program. Once
> the user chooses, the appropriate mini-progran should launch.
OK. Now, is each of these programs in a separate .py file, or
is each a function, each with a different name, inside the same
main .py file?
> 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
In the "separate files" case, assuming you want to run just
one program as chosen by the user:
program_names = ('one', 'two', 'three', 'four')
num_programs = 1+len(program_names)
prompt = "Please enter a number between 1 and %s" % num_programs
while 1:
input_string = raw_input(prompt)
try:
input_code = int(input_string)
else:
if 1<=input_code<=num_programs:
program = program_names[input_code-1] + '.py'
execfile(program)
break
The "several functions" case is not too different:
def one():
# your code goes here
def two():
# your code goes here
# etc, then
functions = (one, two, three, four)
num_programs = 1+len(functions)
prompt = "Please enter a number between 1 and %s" % num_programs
while 1:
input_string = raw_input(prompt)
try:
input_code = int(input_string)
else:
if 1<=input_code<=num_programs:
function = functions[input_code-1] + '.py'
function()
break
> 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??? Even if I define the subprograms as
> functions even, how do I jump to them???
You don't really "jump" in this approach -- you do _invoke_ your
code (in a file or function), but, when that is done (if without
raising exceptions), you get back to the point from where you
had invoked it. Which is why I have the "break" statement, to
end the 'while 1' loop when the operation of the subprogram
is finished. (If errors were to be expected and caught, the
function-call would be placed inside a try/except statement).
Alex
More information about the Python-list
mailing list