Need help with Brittle Morale

code:
def findStrongestEnemy(enemies):
strongest = None
strongestHealth = 0
enemyIndex = 0
# While enemyIndex is less than
while enemyIndex < (len(:
enemy = enemies[enemyIndex]

    if enemy.health > strongestHealth:
        strongest = enemy
        strongestHealth = enemy.health
# Increment enemyIndex
enemyIndex += 1

return strongest

enemies = hero.findEnemies()
leader = findStrongestEnemy(enemies)
if leader:
hero.say(leader)
I’m stuck in a inf loop and I just am trapped basically

Your infinite loop problem is that in the loop part, you are incrementing the index outside of the loop. Just move it inside and so the loop ends correctly.

while enemyIndex < (len(enemies)):
    enemy = enemies[enemyIndex]
    if enemy.health > strongestHealth:
        strongest = enemy
        strongestHealth = enemy.health
    # Increment enemyIndex inside the loop
    enemyIndex += 1 

return strongest

Also, a small tip is that leader does not need to be checked for existance. This is because the right enemy will always be returned from your function if there are at least one enemy. There is no need for that if-statement

enemies = hero.findEnemies()
leader = findStrongestEnemy(enemies)
hero.say(leader)
2 Likes

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