Skip to content
Advertisement

How can I store a value from a list, after user input select’s which list to use?

I want the user to type in a name, then I want to proceed by using specific values based on that input. My current solution is this:

model = input("Attacking Model:")
unit = float(input("How many " + str(model) +"'s:"))

if model == "Warrior":
    bal_Shot = unit * 3
    bal_Skill = (4/6)
    bal_Str = 5
    bal_AP = 2
    bal_Dam = 1
elif model == 'Ravener':
    bal_Shot = unit * 5
    bal_Skill = (4/6)
    bal_Str = 5
    bal_AP = 2
    bal_Dam = 1

However, once I start adding more model names it is going to start to look messy, and I’m assuming there is a more efficient way to do this.

Another solution I have played around with is creating a list for each, then attempting to set the variables to an index of a user inputted list.

model = input("Attacking Model:")

warrior=[3, (4/6), 5, 2, 1]
ravener=[5, (4/6), 5, 2, 1]

bal_Shot = model[0]
bal_Skill = model[1] 
bal_Str = model[2]
bal_AP = model[3]
bal_Dam = model[4]

print(bal_Shot)

But when I do this, it is just returning the letter of the input based on index.

Is it possible to return the correct values based on user input?

Advertisement

Answer

You could put your ẁarrior and ravener lists into a dictionary, then you can simply get the corresponding values with a dictionary lookup:

model = input("Attacking Model:")

lookup = {
  "warrior": [3, 4 / 6, 5, 2, 1]
  "ravener": [5, 4 / 6, 5, 2, 1]
}

bal_Shot = lookup[model][0]
bal_Skill = lookup[model][1]
bal_Str = lookup[model][2]
bal_AP = lookup[model][3]
bal_Dam = lookup[model][4]

print(bal_Shot)

It might make sense to check whether the entered model name actually exists in the lookup dictioary, else you’ll get a KeyError if the user enters a model name that doesn’t exist in the ´ĺookup`:

model = input("Attacking Model: ")

lookup = {
  "warrior": [3, 4 / 6, 5, 2, 1]
  "ravener": [5, 4 / 6, 5, 2, 1]
}
while model not in lookup: # equivalent to "while model not in lookup.keys()"
  model = input("The model name you entered does not exist - please try again: )

bal_Shot = lookup[model][0]
bal_Skill = lookup[model][1]
bal_Str = lookup[model][2]
bal_AP = lookup[model][3]
bal_Dam = lookup[model][4]

print(bal_Shot)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement