Yeti Eater - or more general - why do I need this extra step?

I have solved the level, I’ve cut out a big part of the actual solution from my answer to not make this level too easy for others. But my problem is something else and more general. And it happened to me in earlier levels too.

I tried running the code like this, but nothing happens:

for yeti in range(len(yetis) CENSORED):
    # Attack each enemy while its health greater than 0.
    if yeti:       added this as an extra step to get it to work, but it didnt make a differenc
        while yeti.health > 0:
            hero.attack(yeti)

Then I remembered we often need to add this extra step in levels:

for i in range(len(yetis) CENSORED):
    # Attack each enemy while its health greater than 0.
    yeti = yetis[i]
    while yeti.health > 0:
        hero.attack(yeti)

But why??? Why can’t I just use the word yeti directly instead of i to ‘‘iterate’’ (if this is the correct term) the list of enemies. It just seems like a redundant extra step even though it clearly isn’t, because without it, the code won’t work.

This is because you are mixing the two main ways to do a for loop together (at least the for loops that codecombat uses). They are:

for yeti in yetis: # notice the yetis is an array, and is by itself
    hero.attack(yeti) 

# And:
for i in range(0, len(yetis)): # notice how where once was the yetis array is now range(), which is an array of numbers
    yeti = yetis[i]
    hero.attack(yeti)

Essentially, the for loop goes through each element in an array, each time storing that value inside a variable of choice. Here, either yeti or i. What is contained inside those variables depends on the array you are looping through. In my first example the array is an array of objects, that is the different yetis. In my second example the array which you’re looping through is simply an array of numbers, from 0, to the number of yetis, because that is what range() creates.
So yeti holds an object, which is an individual, attackable yeti, and i holds a number, from 0 to the number of yetis. So when you’re trying to attack yeti in:

You are attempting to attack a number, like 4 lets say.
Whereas in the second one you are creating a variable i which is a number, but then using that number to create a variable yeti, from the yetis array.
I hope that makes sense,
Danny

3 Likes

Perfect explanation, thanks!

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.