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

python how to dynamically print index number of items and print the items

This is my code so far:

things = ['humans', 'fish', 'plants', 'planets', 'stars']

print('These are types of things we learnt so far:')
for thing in things:
    print(thing, end=', ')
print()

print(len(things))
the_input = int(input('Now please enter a number which you want to print: '))
print(f'You have chosen {the_input} which is {things[the_input]}.')

# the unfinished rest:
# the_input = int(input('Now please enter a number which you want to print: '))
# if the_input == the index number of indexes of things list,
# then print:
# You have chosen {the_input} which is {things[the_input]}

This is my expected output:

These are types of things we learnt so far:
1) humans, 2) fish, 3) plants, 4) planets, 5) stars

Now please enter a number which you want to print:
2 # this is the input of terminal, not the output of print(the_input)
You have chosen 2 which is fish.

For this code I don’t know how to do this (there maybe other issues but I’m not yet aware of them):

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

  1. The first print statement to show index_number) each_list_item
  2. to omit the last , which is shown in my code if you run it

>Solution :

Use enumerate and decrease index input:

things = ['humans', 'fish', 'plants', 'planets', 'stars']

print(*[f'{idx}) {thing}' for idx, thing in enumerate(things, 1)], sep=', ', end='\n\n')

the_input = int(input('Now please enter a number which you want to print:\n'))
print(f'You have chosen {the_input} which is {things[the_input-1]}.')

# 1) humans, 2) fish, 3) plants, 4) planets, 5) stars

# Now please enter a number which you want to print:
# 2
# You have chosen 2 which is fish.
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