Ask coding questions

← Back to all posts
How do I treat a user's input as a variable?
Imzecorella (2)

Let's say we have this scenario:

from random import randrange
A = ["Apple", "Apricot"]
B = ["Banana", "Beans"]
C = ["Carrot", "Cauliflower"]
Basket = [A, B, C] #stating what is in the basket
B = input("Input ")
Box = B
Determiner = randrange(0,len(Box)) #getting a random positional value of an item in the Basket
Box = Box[Determiner] #transfoming Basket into the item in the previously acquired slot number

but if I enter "A" as my answer to the input, it is treated like text. I want it to actually mean the same A as that means ["Apple", "Apricot"]

Answered by Wumi4 (541) [earned 5 cycles]
View Answer
Comments
hotnewtop
Wumi4 (541)

Use a map (aka dictionary in Python):

from random import randrange

# First, group your variables into a dictionary like this:
fruit_map = {
  "A": ["Apple", "Apricot"]
  "B": ["Banana", "Beans"]
  "C": ["Carrot", "Cauliflower"]
}

# Then, get the input:
inpt = input("Input: ")

# In this part, access the dictionary like this:
box = fruit_map[inpt]
# If 'inpt' is 'B', this will be the content of the key 'B' (["Banana", "Beans"])

# Finally, do the rest:
determiner = randrange(0, len(box))

box = box[determiner]

Because you ask this question, I am quite sure that you haven't learnt about Python dictionary (short as dict) yet. You should Google about Python dictionaries for more information.

Imzecorella (2)

Thanks, I will try it.