[Tutor] help

alan.gauld@bt.com alan.gauld@bt.com
Wed, 21 Aug 2002 18:47:48 +0100


Hi James,

> things, and the example I am doing right now, looks
> like this so far
> 
> #this is a little program to print out names of an
> #auto dealers departments
> import sys
> def view_options():
>     print "Options"
>     print "'1' Auto Sales"
>     print "'2' Service Center"
>     print "'3' Detail Shop"
>     print "'4' Employment Opportunities"
>     print "'5' To Exit"
> view_options()
>     
> Selection = raw_input("Select a number")
> while Selection != "5":
>     if Selection == '1':
>         print "Family Wagon, Immaculate condition
> $12,995"
>         view_options()
>         Selection = raw_input("Select a number")
etc....

You could shorten this code quite a bit by using a list or dictionary:

options = {"1": ["Auto Sales", "Family Wagon, Immaculate condition"],
           "2": [ "Service center", "Some other message/price"]
           "5": []
          }

Thus to add options you simply edit the options dictionary....

Then write:

def view_options():
  for option in options.keys():
    print option, options[option][0]
  return raw_input("Pick one")

choice = view_options()
while choice != '5':
  print options[choice][1]
  choice = view_options()  
print "Bye!"

> is there any way I could add things, and make them
> stay for the next time the program is run?

You bneed to look at file handling and how to write things to 
a file. Then read the file back in when you start the program.

The approach I describe above is ideal for this since you 
can populate the options dictionary from the file at startup, 
add items during running and then and write the whole dictionary 
back out again at the end.

HTH

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld