当我使用%时,为什么会出现操作数类型错误?

时间:2015-05-17 20:41:48

标签: python python-2.7

我正在制作基于文字的角色扮演游戏,而且我已经坚持了至少一周 这是我创建的敌人类,我现在拥有的功能就是攻击。

class enemy:
    def __init__(self,name,level,health):
        self.name = name
        self.level = level
        self.health = health
    def attack(self):
        print "A %r appears! It wants to fight!" % (self.name)
        player.weapon = (raw_input("What do you attack with? >>").lower())
        while (player.health > 0) or (self.health > 0):
            if (player.inventory.get(player.weapon) > 0):
                player.health = player.health - ( ( randint(0,5) ) +  attack_multiplier(self.level) )
                print "%r strikes! Your health is down to %r" %(self.name, player.health)
                if (player.health > 0) and (self.health > 0):
                    if weapon_probability() == "critical hit":
                        self.health -= (((randint(0,5))) +  (attack_multiplier(weapon_levels.get(player.weapon))) * 2)
                        print_slow( "Critical Hit!")
                    elif weapon_probability() == "hit":
                        self.health -=((((randint(0,5))) +  (attack_multiplier(weapon_levels.get(player.weapon)))))
                        print_slow( "Hit!")
                    elif weapon_probability() == "miss":
                        print_slow( "Miss")
                    print_slow("Enemy health down to %r !") % self.health
                elif player.health <= 0:
                    print_slow("Your health...it's falling")
                    break
                elif self.health <= 0:
                    print_slow( "Enemy vanquished!")
                    break
            else:
                print "You don't have that!"
                player.weapon = (raw_input("What do you attack with? >>").lower())

这是错误:

  File "Central Program.py", line 103, in attack

print_slow("Enemy health down to %d !") % self.health
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

感谢您的帮助,我已经坚持了这么长时间,它变得非常烦人。我觉得解决方案很简单,但我不知道该怎么做

2 个答案:

答案 0 :(得分:4)

您需要将%运算符应用于字符串,而不是print_slow()的返回值。该函数返回NoneNone % self.health会引发错误。

更改

print_slow("Enemy health down to %d !") % self.health

print_slow("Enemy health down to %d !" % self.health)

请注意该结束)括号的位置。您的代码将%应用于错误的对象。

答案 1 :(得分:0)

% self.health放在parantheses