[SOLVED]Problem with function


#1

When i run my code it shows this error.

def findWeakestEnemy():
    enemies = hero.findEnemies()
    weakest = None
    leastHealth = 99999
    enemyIndex = 0
    # Loop through enemies:
    while enemyIndex < len(enemies):
        # If an enemy's health is less than leastHealth:
        enemy = enemies[enemyIndex]
        if enemy.health < leastHealth:
            # Make it the weakest 
            enemy[enemyIndex] = weakest
            # and set leastHealth to its health.
            leastHealth = enemy[enemyIndex].health
            pass
        enemyIndex += 1
        pass
    return weakest

while True:
    # Find the weakest enemy with the function:
    findWeakestEnemy()
    # If the weakest enemy here:
    if weakest:
        # Attack it!
        hero.attack(weakest)
    pass


#2

You do not need to put enemy[enemyIndex] when you redefine weakest, just enemy. Same deal with the lowest health.
Also it is weakest = enemy, not enemy = weakest.
Happy to help :slightly_smiling_face:


#3

Make sure you assign findWeakestEnemy to a variable; For example:

weakestEnemy = findWeakestEnemy()

if weakestEnemy:


#4

Now i’m getting this


#5

Try leastHealth = enemy.health


#6

Now it works! Thanks


#7

Happy to help, @Szymon859! :slightly_smiling_face:


#8

Nice Job @Hellenar. I did not see that!