Can anyone explain the hero.findNearestEnemy() method please

When I put hero.findNearestEnemy() method in the if statement like this

            if hero.findNearestEnemy():
                hero.attack(hero.findNearestEnemy())

My hero attacked enemies when there were enemies around,but when I try this

            if hero.findNearestEnemy() == True:
                hero.attack(hero.findNearestEnemy())

My hero didn’t attack the enemy.So,my question is what is returned by the hero.findNearestEnemy() method? Does it return string(The nearest enemy’s name) or boolean (If enemy does exist,returns True. If not returns False.)?
And why I can use this method in the if statement like in the first example (The hint in the game tell me to do so) and cannot use it like in the second example? In other word,don’t the two examples above equivalent?

I am not good at English, I dont know how to explain my question properly.

findNearestEnemy() returns the object that represents nearest enemy, or None.

The reason you can use it in an if statement is because certain values are considered “falsey” or “truthy”.

For example, the values 0 and None are considered falsey, but None == False is False. :slight_smile:

An ogre object is “truthy” but does not equal the Boolean value of True.

So you could try if hero.findNearestEnemy() != None: but usually it’s easier to leave out the None bit, unless you really need to be specific for some reason.

2 Likes

Thank you so much. :relaxed: