我是python的新手,但不是编程。 If条件被错误处理,并且'else'部分被打印:
if self.health_points <= -1 and self._foo__is_dead == False:
print("Enemy Terminated")
else:
print("Enemy is dead")
我打印出2个变量,并且输入'14'时它们的条件为真。仍然,为什么要处理其他部分? 拜托,请问我哪里出错了?
class Enemy:
health_points = 5
_foo__is_dead = False
def set_hp(self,points_to_set):
if self._foo__is_dead == False:
self.health_points = points_to_set
else:
print("Enemy is already dead")
def attack(self):
print("Hit confirmed")
self.health_points -= 1
if self.health_points <= -1:
self._foo__is_dead = true
print(self._foo__is_dead)
print(self.health_points)
if (self.health_points <= -1 and self._foo__is_dead == False):
print("Enemy Terminated")
else:
print("Enemy is dead")
#Connected to pydev debugger (build 172.3968.37)
#Enter hit points for first enemy14
#Hit confirmed
#False
#13
def reveal_hp(self):
if self._foo__is_dead == False:
print(self.health_points, " health points remaining")
else:
print("Enemy is already dead")
first_enemy = Enemy()
try:
one_hp = int(input("Enter hit points for first enemy"))
except ValueError or one_hp > 100:
print("Enter only numerical values and less than 100")
exit(0)
first_enemy.set_hp(one_hp)
first_enemy.attack()
first_enemy.reveal_hp()
答案 0 :(得分:0)
你还没有正确地思考逻辑。目前你已经设定好了如果敌人没有健康并且没有死亡,那么说他们已经被杀死了。如果没有,说他们已经死了,即使他们还有健康。您只需添加最终检查。
如果您交换它,它应该正常工作:
if (self.health_points <= -1 and self._foo__is_dead == False):
print("Enemy Terminated")
else:
print("Enemy is dead")
对于这样的事情:
if self.health_points <= -1:
if not self._foo__is_dead:
self._foo__is_dead = True
print("Enemy Terminated")
else:
print("Enemy is dead")
else:
print("Enemy has {} health remaining".format(self.health_points))