-2

I am a relatively new programmer and I can not figure out how to make variables for certain elements in a list. I am trying to do this so I can ask for a certain number and then the console will print a certain element of the list. This is a something I have to do for practice before I can move on to the next level of python. This programming is done through a site called codesters.

Here are the directions I was given to make this program:

  1. There is a list of 5 foods (use any name).
  2. Print to the console each food by using an index variable to access each element in the list. (HINT: For loop)
  3. Ask the user for a food number (location in the list), then print out that food. (E.g. The list are A, B, C, D, E and food number 1 is A)

And this is the code I have so far:

mylist = ["cherry","cake", "rice", "bannana", "strawberry"]

for x in mylist:
    print(x)

mylist.append(input("Please enter a food number:"))

Thanks for any help.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
LIlkahuna
  • 17
  • 3
  • 1
    Step #3 doesn't say anything about `append`ing. – Scott Hunter Jul 13 '21 at 19:42
  • Instead of `append`ing to your list, you want to index into the list: `print(mylist[int(input(...))])`. Note that `input` returns a `str`, so you have to cast it to an `int` in order to use it as a list index. – 0x5453 Jul 13 '21 at 19:43
  • Welcome to SO! Please take the [tour] and read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) as well as [ask] in general. For direction 2, you seem to have missed the point: you need to use an index variable. For direction 3, your code isn't even close. You can [edit] your question if needed. – wjandrea Jul 13 '21 at 19:49
  • Does this answer your question? [Using an index to get an item](https://stackoverflow.com/questions/3019909/using-an-index-to-get-an-item) – wjandrea Jul 13 '21 at 19:55
  • Also: [How to convert strings into integers in Python?](/q/642154/4518341) – wjandrea Jul 13 '21 at 20:07

3 Answers3

1

It looks like you're trying to iterate through the index of your list. Do so using range:

mylist = ["cherry","cake", "rice", "bannana", "strawberry"]

for i in range(len(mylist)):
    print(mylist[i])

Similarly, you can ask a user for input and print a specific index:

while True:
    # Ask for input
    idx = input('Which food do you want to see?')

    # only allow numbers
    if not idx or not idx.isnumeric():
        print('Please enter a valid number')
        continue

    # convert to int
    idx = int(idx)
    
    # more validation – only accept numbers in valid range
    if idx<0 or idx>=len(mylist):
        print(f'Please enter a number between 0 and {len(mylist)-1}')
        continue

    # otherwise
    print(f'Your food is: {mylist[idx]}')
    break
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • 1
    Just a stylistic note: `range(len(mylist))` is an antipattern. Generally `for item in mylist` is preferred, or if you really need a list index, `for i, item in enumerate(mylist)`. – 0x5453 Jul 13 '21 at 19:46
  • Agreed. However, from context of Q, sounds like index only was to be provided @0x5453 -> likely to employ python in a way to make it comparable to other languages. – Yaakov Bressler Jul 13 '21 at 19:50
  • @ybressler_simon this solved my problem but i have one question on how to make it so the range for a valid number is 1 through five so like cherry is number 1 Thanks so much for the help. – LIlkahuna Jul 13 '21 at 20:32
  • If you're referring to the input section, that would be a quick `idx - 1` computation. @LIlkahuna – Yaakov Bressler Jul 13 '21 at 20:37
  • @ybressler_simon where would i add that? Would it be at the idx<0? – LIlkahuna Jul 13 '21 at 20:52
  • You'd prob want to add after the line where `idx` is turned into an `int`. @LIlkahuna – Yaakov Bressler Jul 13 '21 at 21:15
1

As noted by @ybressler-simon, the instructions refer to an index variable, because items in a list can be accessed by their position within the list, and a variable that picks out an item by position is often called an index.

>>> mylist = ['hotdish', 'lutefisk']
>>> mylist[0]
'hotdish'

>>> mylist[1]
'lutefisk'

>>> x = 0
>>> mylist[x]
'hotdish'

Use the len() function to get the number of items in a list, its length.

>>> len(mylist)
2

Use the range() function to produce a sequence of numbers counting up from 0.

>>> list(range(2))
[0, 1]

Then put the parts together and you're all set!

TMBailey
  • 557
  • 3
  • 14
1
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]

for count, value in enumerate(mylist, start=1):
    print('{} - {}'.format(count, value))

choice = int(input("Please enter a food number: "))

print(mylist[choice-1])

Will result:

1 - cherry

2 - cake

3 - rice

4 - bannana

5 - strawberry

Please enter a food number: 5

strawberry

marckesin
  • 71
  • 4