我知道这听起来很愚蠢,而且可能简单得离谱,但我只需要一种直接、快速的方法,因为我可能需要在整个代码中使用它。 我会在这里粘贴我的代码,也请忽略它继续关于 Minecraft 的事实;我个人无法忍受这款游戏,但在我的学校里它有点像一个流传的笑话。不过,实际的代码实际上是我只是在尝试为我的 GCSE 考试做准备。是的,我知道它不是最好的,但我只学习了一个星期的 python。 Pastebin to my code: http://pastebin.com/QWtWJMvV
这部分代码是我阻止“健康”变量超过 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
因为那太荒谬了。
最佳答案
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)
至于你的其他问题,你可以更换大部分elif
塔。与 health += healthRecover0
.
关于Python:如何阻止变量超过某个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884030/