[Tutor] how to do "program chains"

Andrei Kulakov ak@silmarill.org
Sat, 13 Apr 2002 13:59:38 -0400


On Sat, Apr 13, 2002 at 01:16:42PM -0400, VSOFTSMITH@aol.com wrote:
> i am used to working in an environment where the user signs on with a 
> password and is presented with a menu of choices of independent things they 
> might want to do, eg
> 
>        1. admit patient
>        2. display patient
>       3. production run
> 
> with each choice a new program is called and executed. when complete it 
> returns to the menu from which it was called.
> 
> some program transfers like to "production run" above are other menus.
> there may be 300 programs that are accessible this way.
> each program is small and easily maintained independently of the others
> 
> how do i do this in python? example code somewhere?
>
def admit_patient():
    [...]

def display_patient():
    [...]

def production_run():
    [...]

use_dict = {
    1: admit_patient,
    2: display_patient,
    3: production_run,
}

while 1:
    answer = raw_input("""
    1. admit patient
    2. display patient
    3. production run

    Enter number: """)

    try:
        a = int(answer)
        use_dict[a]()   # run needed function.
    except (ValueError, IndexError):
        print "Illegal response"
        continue


Each function could actually be in a separate module for easier
maintainance (if they grow real big). The only hockey thing here is the
line use_dict[a](). What happens here is that use_dict[1] (for instance)
becomes admit_patient. admit_patient with added () becomes
admit_patient(), which runs the respective function.


 - Andrei


> 
> thanks for any help
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org