Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

[SOLVED] Why do you need 'if enemy:'?

(Sorry I’m not used to the site, so I couldn’t include indentations for the code)

I just finished the dungeon map and entered the forest. (python)
They gave me the second book which contains ‘if’ method.
And I cleared some defence maps using this code below.

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

This code let my hero keep killing enemy when they pop up.

But why do you even need ‘if enemy’ at all in the first place?
(I know those maps were for teaching ‘if’ code, but…)
Shouldn’t just this code below do the same job?

while True:
enemy = hero.findNearestEnemy()
hero.attack(enemy)

It’s like, the hero should keep searching and finding a nearest enemy and attack it over and over, isn’t it?
But the code didn’t work at all. Hero did nothing but got beaten. Why is it so? What am I missing?

Hello, welcome to the CodeCombat forum. This post will help with formatting the code correctly in the forum.

To answer your question, when you give a command the code needs to complete the command before it will continue. Since your enemy variable didn’t find anyone, the hero doesn’t have anyone to attack. But the hero can’t do anything else until it attacks the non-existent enemy which stops your code from continuing.

The if enemy checks to see if there is a value in the variable enemy. If there is an enemy it returns True, now attack. If no enemy False skip the attack and check for another enemy. This ensures there is an enemy to attack before calling the command to attack so your code doesn’t lock up.

1 Like

Thank you very much!!! :smiley: