Anton Filip Svensson
Anton Filip Svensson

Reputation: 23

Using User Input to Index List in Python

I can't understand what I am doing wrong with this method. It is called from another in class method as such:

def equip_menu(self): # this is not the actual method, but equip_choice is used only in the following lines
    #snipped code
    equip_choice = Input("Input the number of the item you want to equip:\n")
    self.select_from_list_equip(equip_choice) 

and this is the method throwing error:

def select_from_list_equip(self, equip_choice): # Trying to select item in list self.backpack
    item_to_equip = self.backpack[equip_choice]
    print("*DEBUG* Equip chosen:", item_to_equip.name)
    playeritems.equip(item_to_equip)

I get the error:

"classes.py", line 109, in select_from_list_equip
    item_to_equip = self.backpack[count]
TypeError: list indices must be integers or slices, not str"

So I tried making equip_choice an integer, even though I just try inputting digits without decimals and still get the error. I am in the opinion that I am not trying to use a string as list index, but obviously I am wrong. So I tried to force equip_choice to become an integer like this:

def select_from_list_equip(self, equip_choice):
    int(equip_choice)
    item_to_equip = self.backpack[equip_choice]
    print("*DEBUG* Equip chosen:", item_to_equip.name)
    playeritems.equip(item_to_equip)

But I still get the same identical error. Why can't I use the value of equip_choice as list index? I must be missing something very obvious and basic I am blind to?

Upvotes: 0

Views: 1467

Answers (1)

user1558604
user1558604

Reputation: 987

Input() returns a string. You will need to use int() to convert to an integer.

input() resource

Upvotes: 2

Related Questions