How to select an item from a list in python
Question:
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
- Harry
- Marg
- 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):
Answers:
You can use enumerate
:
Employees=['Harry Grapes', 'Marg Plum', 'Monica Nguyen']
for pos, employee in enumerate(Employees):
# i starts from 0
print(f"{str(pos+1)}. {employee.split()[0]}")
choice = int(input('Choose from options: '))
print('You chose ' + Employees[choice-1])
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))
Employees = ['Harry Grapes', 'Marg Plum', 'Monica Nguyen']
print("Please select the employee")
for i in range(len(Employees)):
print(i+1,'. ',Employees[i])
choice = int(input())
selectedEmp = Employees[choice-1]
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
- Harry
- Marg
- 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):
You can use enumerate
:
Employees=['Harry Grapes', 'Marg Plum', 'Monica Nguyen']
for pos, employee in enumerate(Employees):
# i starts from 0
print(f"{str(pos+1)}. {employee.split()[0]}")
choice = int(input('Choose from options: '))
print('You chose ' + Employees[choice-1])
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))
Employees = ['Harry Grapes', 'Marg Plum', 'Monica Nguyen']
print("Please select the employee")
for i in range(len(Employees)):
print(i+1,'. ',Employees[i])
choice = int(input())
selectedEmp = Employees[choice-1]