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.
CodePudding user response:
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
CodePudding user response:
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!