Search code examples
pythonvariablesuser-input

Taking user input as string and printing a variable Python


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.


Solution

  • 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