Whats the difference?

This is the code given for the problem im currently on. I have no problem solving this problem the way they want it but I wanted to change the code.

‘’‘
while True:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
if hero.now() > 15:
break
’’’

Is their any reason why I can not put the hero.now() function for the condition of a while loop? How can the if statement use it if the while cant? When I try and run this code it says my program is running slow or theirs an infinite loop. I dont really understand how the hero.now() function works. Its supose to return a number. Thats why im assuming it works fine in the if statement. I dont need a correction to the solution I just want to know why im getting an infinte loop.

‘’‘
while hero.now() < 15:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
’’’

Sorry I had to repost. XD

This is the code given for the problem im currently on. I have no problem solving this problem the way they want it but I wanted to change the code.

while True:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
if hero.now() > 15:
break

Is their any reason why I can not put the hero.now() function for the condition of a while loop? How can the if statement use it if the while cant? When I try and run this code it says my program is running slow or theirs an infinite loop. I dont really understand how the hero.now() function works. Its supose to return a number. Thats why im assuming it works fine in the if statement. I dont need a correction to the solution I just want to know why im getting an infinte loop.

while hero.now() < 15:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1

check this / search for infinity loop

at the end add

hero.wait( 0.1 )

probably will help

Ive read the post. Thanks. I see why waiting could help. I guess loops essentially are iterating super fast and thats why im slowing down. While I dont have an item to use wait. This article really did help me understand what was happening. Much appreciated. :smile:

:laughing: Wow the very next problem says “Make sure your always doing something in a while-loop or you might get an infinite loop error.” Maybe put that statement a bit sooner for the ambitious coders that want to implement a different method. Look they even put in an event so an infinite loop doesnt occur. :laughing:

while defeatedOgres < 6:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)
        defeatedOgres += 1
    else:
        hero.say("Ogres!")