[Tutor] User selection as both string and int

Brian van den Broek bvande at po-box.mcgill.ca
Wed Dec 15 04:44:50 CET 2004


Marc Gartler said unto the world upon 2004-12-14 22:13:
> I am trying to have a user select from amongst a list of items, and then 
> make use of that choice later on as both a string (e.g. "you chose 
> _____").  My function currently allows for a numerical choice, but I am 
> not sure how to return it as the item (e.g. apple) rather than the 
> integer corresponding to the position in the list:
> 
> def get_material(mylist):
>     mycount = 1
>     for item in mylist:
>         print mycount, item
>         mycount = mycount + 1
>     material = raw_input("Please select material:")
>     myposition = int(material) - 1
>     return myposition
> 
> fruit_list = ['apple', 'orange', 'banana']
> 
> fruit = get_material(fruit_list)
> 

Hi Marc,

Since fruit_list is a list, you can 'fetch' an element out of it like so:
fruit_list[index]
where index is an integer.

Your function returns an integer. So, for the minimal change to get what 
you want done, try replacing your last line with these two:
fruit = fruit_list[get_material(fruit_list)]
print fruit

Best,

Brian vdB


More information about the Tutor mailing list