Reputation:
I am experimenting with replacing a block of if/ elif statements which are all very similar with a for loop that changes the conditions of one for loop a few times.
My original if/ elif statements are for an item system of an RPG I am coding. Each type of item can only go in certain slots of the inventory.
def PickUpItem(self): #Adds an item to the inventory in a space depending on its type
if self.Type == 1 and not Inventory[0]: #Type 1 is a weapon type, 2 is for shields, etc.
Inventory[0] = self #Sets the weapon inventory slot to the object
elif self.Type == 2 and not Inventory[1]:
Inventory[1] = self
elif self.Type == 3 and not Inventory[2]:
Inventory[2] = self
So, here is the code I am trying to replace the previous with so that it will check each of the if/ elif statements' pairs of conditions:
def PickUpItem(self):
for i, j in range(1, 4), range(3):
if self.Type == i and not Inventory[j]:
Inventory[j] = self
I think this should work, but I get the error:
for i, j in range(1, 4), range(0, 3):
ValueError: too many values to unpack (expected 2)
Upvotes: 0
Views: 60
Reputation: 27802
You can set j = i - 1
in your loop:
for i in range(1,4):
j = i - 1
if self.Type == i and not Inventory[j]:
Inventory[j] = self
Upvotes: 0
Reputation: 78590
What you're looking for is zip:
for i, j in zip(range(1, 4), range(0, 3)):
The reason (as you could confirm in an interactive terminal) is that zip(range(1, 4), range(0, 3))
has the value [(1, 0), (2, 1), (3, 2)]
.
However, note that your code could be much more easily written as
if not Inventory[self.Type - 1]:
Inventory[self.Type - 1] = self
Upvotes: 1