def msg2(n):
a = "You selected"
if n == 1:
return (a, "ITEM 1")
if n == 2:
return (a, "ITEM 2")
def selectItemFrom(menu):
'''Returns identification of the selected item.'''
# Build the prompt.
prompt = 'Please, type 1-' + str(len(menu)) + ': '
# Display the menu once.
print
for n, txt in enumerate(menu):
print '{0} - {1}'.format(n + 1, txt) # zero-based to one-based
print
selected = 0
while selected < 1 or selected > len(menu):
# Ask the user and get his/her input.
selected = raw_input(prompt)
# Convert the typed-in string to the integer value.
try:
selected = int(selected)
except:
selected = 0
return menu[selected - 1] # one-based to zero-based
if __name__ == '__main__':
print 'What do you prefer?'
menu = ('milk', 'egg') # Here a tuple but it can also be a list.
answer = selectItemFrom(menu)
print 'OK, you prefer', answer
print '\nWhat type of pasta do you like?'
answer = selectItemFrom(('spaghetti', 'spaghettini', 'macaroni', 'farfale'))
print 'OK, you prefer', answer
c:\tmp\___python\ezzadin>python a.py
What do you prefer?
1 - milk
2 - egg
Please, type 1-2: help
Please, type 1-2: xxx
Please, type 1-2: 5
Please, type 1-2: 2
OK, you prefer egg
What type of pasta do you like?
1 - spaghetti
2 - spaghettini
3 - macaroni
4 - farfale
Please, type 1-4: 0
Please, type 1-4: 5
Please, type 1-4: 3
OK, you prefer macaroni