Python:如何阻止变量超过某个值?

2024-10-03 09:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这听起来很愚蠢,而且可能非常简单,但我只需要一种直接、快速的方法,因为我可能需要在整个代码中使用它。 我将把我的代码贴在这里,也请忽略一个事实,那就是它是关于Minecraft的;我个人无法忍受这个游戏,但它在我的学校里是一个持续的笑话。不过,真正的代码是,我只是在努力练习,为我的普通中等教育证书做好准备。是的,我知道这不是最棒的,但我只学了一个星期的python。Pastebin to my code: http://pastebin.com/QWtWJMvV

这部分代码是我阻止“health”变量超过20:if health < 20: health = 20的方法。我不知道这是不是最有效的方法,或者它是否有效。你知道吗

最后一件事,如果有人能给我一个更简单的写作方法,那就太棒了:

healthRecover0 = (randint(1,10))
if health == 20:
    healthRecover0 = (randint(0,0))
elif healthRecover0 == 1:
    health + 1
elif healthRecover0 == 2:
    health + 2
elif healthRecover0 == 3:
    health + 3
elif healthRecover0 == 4:
    health + 4
elif healthRecover0 == 5:
    health + 5
elif healthRecover0 == 6:
    health + 6
elif healthRecover0 == 7:
    health + 7
elif healthRecover0 == 8:
    health + 8
elif healthRecover0 == 9:
    health + 9
elif healthRecover0 == 10:
    health + 10

因为这太荒谬了。你知道吗


Tags: to方法代码游戏if学校事实笑话
3条回答

This part of the code was my way of stopping my 'health' variable from exceeding 20: if health < 20: health = 20. Whether or not that is the most efficient way or if it even works is beyond me.

你把这个倒过来。你正在检查你的健康状况是否小于20,然后将其设置为20。如果你想确保它不超过20,把鳄鱼转过来:

if health > 20: health = 20

这是一个完美的写作方法,但你也可以用以下方法之一来写:

health = 20 if health > 20 else health
health = min(20, health)

至于你的另一个问题,你可以用health += healthRecover0替换你的大部分elif塔。你知道吗

你想用

if health > 20: health = 20

很好(除了使用<而不是>)。至于你问题的第二部分,这应该有用:

healthRecover0 = randint(1,10)
if health < 20:
    health += healthRecover0

pythonic的方法是使用@propertydecorator。您可以提供在setter中检查max health的逻辑:

class Monster(object):

    def __init__(self, initial_health=20, max_health=20):
        # Private property which stores the actual health
        self._health = initial_health
        self.max_health = 20

    @property
    def health(self):
        return self._health

    @health.setter
    def health(self, value):
        if value > self.max_health:
            value = self.max_health
        self._health = value

这样就不能为该值指定大于最大可能值的值:

a = Monster()

assert a == 20   # Intitial value is 20

a.health = 10
assert a == 10   # Changed to 10

a.health = 30
assert a == 20   # we set it to 30 but is capped to 20 max

相关问题 更多 >