Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get value of a list by enumerate numbers

i want to get values from a list by choosing enumerate numbers (1, 2 or 3) on the display, so the choosen variable will results a value from the list not the characters that i type from the input

List = ['apple', 'berry', 'cherry']

List_Display = '\n'.join(['[{}]{}'.format(n,i) for n, i in (enumerate(List,start=1))])

print(List_Display)

choosen = []

choose = input('Enter choices: ')

if choose in List_Display:

    choosen.append(choose)

    print('choosen:',choosen)

else:

    print('No item choosed') 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You will have to convert your input to an integer and adjust it with -1 because the index of a list starts with 0. Then you have to check if you have a valid index.

fruits = ['apple', 'berry', 'cherry']

fruits_display = '\n'.join([f'[{i}]{n}' for i, n in (enumerate(fruits, start=1))])
print(fruits_display)

selected = []
user_input = int(input('Enter choices: ')) - 1
if 0 <= user_input < len(fruits):
    selected.append(fruits[user_input])
    print('choosen:',selected)
else:
    print('No item choosed')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading