# Calculate the total health of all the ogres. def sumHealth(enemies): # Create a variable and set it to 0 to start the sum. totalHealth = 0 # Initialize the loop index to 0 enemyIndex = 0 # While enemyIndex is less than the length of enemies array while enemyIndex < len(enemies): # Add the current enemy's health to totalHealth totalHealth = enemies[index].health # Increment enemyIndex by 1. index +=1 return totalHealth # Use the cannon to defeat the ogres. cannon = hero.findNearest(hero.findFriends()) # The cannon can see through the walls. enemies = cannon.findEnemies() # Calculate the sum of the ogres' health. ogreSummaryHealth = sumHealth(enemies) hero.say("Use " + ogreSummaryHealth + " grams.")
# Add the current enemy's health to totalHealth
It doesn’t say, add the current enemies health to total health. It says enemy’s health (singular possessive, not plural). Yet, you haven’t defined enemy (singular). While iterating through arrays, you’re taking the health of each enemy (one at a time for each iteration) and adding it to totalHealth. What you’ve done is an assignment. You’ve reassigned totalHealth as a variable with a new definition.
# Increment enemyIndex by 1.
Look at this closely. Look at the comments and then look at what you wrote.
not that. There isn’t anything which defines index. read the text right above
index += 1
No, that would be an assignment of enemies[enemyIndex] to the variable currentEnemy. In order to, “add the current enemy’s health to totalHealth,” you must define enemy first. I’m sure you’ve done this before in previous levels when iterating through arrays.
enemy = enemies[enemyIndex]