Accessing a list in raw_input


#1



I would like to access my two lists inside the raw_input prompt.

I want the user to be asked "Would you like chocolate or vanilla". and then "Would you like blueberry or strawberry". I want to prompt the user 4 times and then print their selections to the console.


muffins= ['chocolate', 'blueberry', 'poppyseed', 'fern']
cake= ['vanilla', 'strawberry', 'ice cream', 'flute']

for a,b in zip(muffins,cake):
    choice == raw_input("Would you rather have" muffins[a] "or" cake[b])
    print 'I would like' choice
else:
    print 'Have a nice lunch!'


#2

you can simple write a if condition?

if a == choice:

and same for b, pretty straight forward. a and b will hold the items in the list, and choice the result of prompt, pretty simple comparison should do


#3

But the main problem I am having is accessing muffins[a] inside the raw_input. The error comes in this line:

choice == raw_input("Would you rather have" muffins[a] "or" cake[b])


#4

oh, well you need to join a string and a variable together with a plus sign:

example = "hello"
print(example + " world")

#5

Thank you that solved my problem. However now I am getting an error telling me the list indices must be integers.

Python doesn't want me to use muffins[a] to access the first element of the list. But I thought that was how the 'zip' function worked.


#6

no, zip allows you to run two loops at the same time. a and b already contain the list items (not indexes), if you want to use indexes you should use range()


#7

Thank you, I finally got the code to work with no errors! I have one more question though. Right now the user is prompted and after they choose chocolate or vanilla a response is printed to the console saying 'I would like chocolate'.

Instead I would like the user to be prompted 4 times and given choices. Only after the final question do I want their choices to be printed to the console.


#8

create a list, use append to append the items to the list, then use a loop to list there choices