Syntax question on Medical Attention


#1

Hello,
I am used to Java type of syntax but I started CodeCombat in Python and got used to it. I did two versions of the codes and noticed one worked and the other didn’t. I couldn’t make sense of why the other version couldn’t work. Take a look and please shed some lights. Thank you.

working

> loop:
>     currentHealth = self.health
>     healingThreshold = self.maxHealth / 2
>     # If your current health is less than the threshold,
>     # move to the healing point and say, "heal me".
>     # Otherwise, just attack enemies.
>     enemy = self.findNearestEnemy()
>     if  currentHealth < healingThreshold :
>         self.moveXY(65, 46)
>         self.say("heal me")
>     **elif enemy :**
>         self.shield()  
>         self.attack(enemy)
>         self.attack(enemy)
>         self.attack(enemy)

not working

> loop:
>     currentHealth = self.health
>     healingThreshold = self.maxHealth / 2
>     # If your current health is less than the threshold,
>     # move to the healing point and say, "heal me".
>     # Otherwise, just attack enemies.
>     enemy = self.findNearestEnemy()
>     if  currentHealth < healingThreshold:
>         self.moveXY(65, 46)
>         self.say("heal me")
      **else:**
        self.shield()  
        self.attack(enemy)
        self.attack(enemy)
        self.attack(enemy)

Notice the Bold part in else portion.
My humans didn’t survive in the nonworking one. I looked up the documentation and changed it to “elif enemy”.
What was interesting was, the error message for not working one tells me there was no target for me the attack. How so, enemy was defined outside of the if/else loop. So I suppose it would work.

any ideas?

Merry Christmas by the way!


#2

The problem here is that there might not be an enemy, and you might also not have to heal, in which case, your hero doesn’t know what to do because he doesn’t have to do anything that you have said. You need the elif enemy because this means that if there is an enemy, then shield and attack enemy. Merry Christmas, or Hanakkuh, or Kwanzaa, or whatever you celebrate. Happy holidays (let’s just leave it at that :stuck_out_tongue:).


#3

There are different ways of saying elif enemy, but for the most part, you need that line. another way you could do it if you don’t like doing it with elif enemy:

else:
    if enemy:
#Your code goes here

#4

Oh ok. I use JavaScript, but I know a little bit about Python. Guess I need to know more. Haha