[Tutor] Re: Suggestions for cleaner code
Lee Harr
missive@hotmail.com
Tue Jul 8 20:20:04 2003
# list of tuples (description, message)
# make sure your "exit" choice is last in the list
messages = [('Greeting', 'Hello.'),
('Discussion', 'I should have paid more attention in math
classes.'),
('Question', 'Why did I sleep through class?'),
('Extend', 'Now with simpler extensibility!'),
('Farewell', 'Farewell'),
]
def show_choices():
print 'Choose one of the following: '
# starting with python2.3, use enumerate
n = 1
for description, message in messages:
print '%2s %s' % (n, description)
n += 1
def show_message(option):
description, message = messages[option-1]
print
print message
print
def get_input():
# raw_input is recommended over input
# in fact, don't use input at all
while 1:
try:
option = int(raw_input('Enter %s - %s : ' % (1, len(messages))))
if not (1 <= option <= len(messages)):
continue
if option == len(messages):
option = 0
return option
except ValueError:
pass
def main():
while 1:
show_choices()
option = get_input()
if option:
show_message(option)
else:
show_message(len(messages))
break
if __name__ == '__main__':
main()
_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail