# Shine Getter: Needing a better understanding of arrays

#1

Here is my code:
coinIndex = 0
loop:
coins = self.findItems()
coin = coins[coinIndex]
if coin.value == 3:
self.moveXY(coin.pos.x, coin.pos.y)
coinIndex += 1
else:
coinIndex += 1
pass

I can solve this level is a different fashion easily, but I was hoping to know why my character picks up 8 gold coins perfectly and then the “tmp26 is undefined” error comes up on my “if coin.value == 3” line. I’m not certain if I need to use a while loop to compare the coins to coinIndex. Any insights on what could be fixed on this code is appreciated.

#2

apologies for the indenting of the code. Its my first post and it looks great in the preview but not in the posting. Another thing to learn I guess

#3

I think it says in the guidelines, but did you try posting your code with 3 ` ? Then it should show up right with all the indents.

ex:

``````enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
``````

I’m still new but the only thing that looks different from what I’ve tried is putting the coins=self.findItems() above the loop:

#4

If there’s only 10 coins, and coinIndex goes to 11, your code will break.

Rhetorical Question: If you pick coins[0], what happens to coins[0] when you next run self.findItems()?

Once you find the answer to that question, you should be able to deduce why your code broke.

#5

@chale - Try replacing if coin.value == 3 with: if coin and coin.value == 3.

This checks for coin also. I think your loop was breaking because of unavailability of coin of value 3 and trying to pick it up.

Also notice that in my correction ‘if coin and coin.value == 3’, coin comes first and them coin.value. This is the order how the python compiler reads it. Only when coin is true, coin.value == 3 is checked. So, no errors for coin not being on the map.

What I suggested is equivalent to:

``````if coin:
if coin.value == 3:
self.moveXY (coin.pos.x, coin.pos.y)
``````

Cheers

#6

Thanks for the explanation. It helps for the specific level, but more importantly helps me to understand how arrays work.

#7

I’ll have to try that. After all the work to get the indenting right it is nice to have a way to get it to show up right in the forums.