Home > Enterprise >  How to select an item from a list in python
How to select an item from a list in python

Time:08-22

I am have a list as shown
Employees=['Harry Grapes','Marg Plum','Monica Nguyen']
I would like to create a selection feature that allows the user to select the Employee on a menu.
Something like:

Please select the employee

  1. Harry
  2. Marg
  3. Monica

If they type 1 it selects Harry from the list.
Atm I just cycle through all the employees with a for loop.
for CurrentEmployee in range(3):

CodePudding user response:

you can use enumerate:

Employees=['Harry Grapes', 'Marg Plum', 'Monica Nguyen']

for pos, employee in enumerate(Employees):
    # i starts from 0
    print(f"{str(i 1)}. {j.split()[0]}")
    
choice = int(input('Choose from options: '))

print('You chose '   a[choice-1])

Hope you got your answer, pls upvote as its my first answer.

CodePudding user response:

you can store the name elements to dictionary and get the data from the user to print the name.

Employees = ['Harry Grapes', 'Marg Plum', 'Monica Nguyen']

names = []
for i in Employees:
    names.append(i.split()[0]) # take first word of each element
names_dict = {}
for index, word in enumerate(names, start=1):
    names_dict[index] = word  # store index and the elements in dict
print(names_dict)
user = int(input('enter the number:'))
print(names_dict.get(user))
  • Related