0

I was trying to take a user input and then convert that input into a variable to print out a list.

food_list = ["Rice", "l2", "l3"]
Rice = []
l2 = []
l3 = []
answer = input("What item would you like to see from the list")
if answer in food_list:
      print("answer")

I wanted the output to be to print the Rice list, not just the string "Rice" like it has been. The input will take it as a string but I want to turn the input to the list variable.

HunterP56
  • 3
  • 4
  • What is your expected output ? – k33da_the_bug Feb 25 '22 at 19:12
  • 2
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) or maybe https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string – JonSG Feb 25 '22 at 19:16
  • The code as posted is missing the close quotes in line 1 after the word Rice" and therefore reports an error. Once that is fixed the code as written will always return Rice if the Response is Rice. Otherwise, it returns nothing. What is the desired functionality of the program? – Carl_M Feb 25 '22 at 19:20

2 Answers2

0

Python's in keyword s powerful, however it only checks list membership.

You want something like this:

food_list = ["Rice", "Cookies"]
answer = input("What item would you like to see from the list")

# if the food is not in the list, then we can exit early
if answer not in food_list:
  print("Food not found in the list")

# we know it's in the list, now you just filter it.
for food in food_list:
  if food == answer:
    print(food)

Happy coding!

Sienna
  • 1,570
  • 3
  • 24
  • 48
0

You can do this with a dictionary:

~/tests/py $ cat rice.py
food_list ={"Rice":"Rice is nice" }

print("What item would you like to see from the list")
answer = input(": ")
if answer in food_list.keys():
      print(food_list[answer])
~/tests/py $ python rice.py
What item would you like to see from the list
: Rice
Rice is nice