[Tutor] (no subject)
Alan Gauld
alan.gauld at freenet.co.uk
Sun Mar 6 00:56:53 CET 2005
> ## Now the fun part ##
> ## We define a dictionary options that stores the strings that the
user
> would input as keys. The values
> ## are the functions that we just defined
>
> options = {"3":altexit, # Notice no parenthesis--we don't
want to
> call the functions when putting them in the dicionary!
> "2":instruct,
> "1":game,
> "":choice}
>
> while 1:
> play = raw_input("What is your choice? ")
> if play in options.keys():
> options[play]()
> else:
> print "\nYou need to pick 1, 2 or 3 or hit enter to see
choices\n"
Or more pythonically:
while 1:
play = raw_input(...
try: options[play]()
except KeyError: print "\nYou need...."
Avoids the search of keys each time, and follows the idiom
of "its better to ask forgiveness"
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list