Movatterモバイル変換
[0]ホーム
In the Absence of a GoTo Statement: Newbie needs menu-launcher to choose amongst sub-programs
Alex Martellialeaxit at yahoo.com
Fri Apr 13 15:00:58 EDT 2001
"Ron Stephens" <rdsteph at earthlink.net> wrote in messagenews: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, thereis 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, oris each a function, each with a different name, inside the samemain .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? WithIn the "separate files" case, assuming you want to run justone 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_programswhile 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) breakThe "several functions" case is not too different:def one(): # your code goes heredef two(): # your code goes here# etc, thenfunctions = (one, two, three, four)num_programs = 1+len(functions)prompt = "Please enter a number between 1 and %s" % num_programswhile 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_ yourcode (in a file or function), but, when that is done (if withoutraising exceptions), you get back to the point from where youhad invoked it. Which is why I have the "break" statement, toend the 'while 1' loop when the operation of the subprogramis finished. (If errors were to be expected and caught, thefunction-call would be placed inside a try/except statement).Alex
More information about the Python-listmailing list
[8]ページ先頭