我刚接触python,我试着制作一个基于文本的小游戏,我列出了玩家的健康状况,当我试图在函数中编辑变量时,它不会改变全局变量,当我尝试使用全局命令将它定义为全局变量时,它说参数已经是一个全局变量,而返回也不起作用?
import random
health = 100
dHealth = 1000
def attack(dHealth):
attack = random.randint(5,50)
dHealth = dHealth - attack
print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
attack(dHealth)
print(dHealth) 我希望变量从1000变为995到950之间的数字。
发布于 2022-03-26 12:51:41
最好的解决方案是不要将其用作全局变量。attack应该取一个值并返回更新的值。
import random
health = 100
dHealth = 1000
def attack(monster, health):
attack = random.randint(5,50)
health = health - attack
print("You dealt", attack,"damage, the ", monster, " has", health,"health left!")
return health
dHealth = attack("dragon", dHealth)
print(dHealth) 因为从理论上讲,attack不再是专门针对龙的健康的,所以它需要一个额外的参数来命名为调用print而受到攻击的怪物。
发布于 2022-03-26 12:49:22
因此,您需要指定inside函数,即它是要更改的全局变量。代码如下所示:
import random
health = 100
dHealth = 1000
def attack(): # If you pass dHealth here, it only changes the local instance and not
# the global one
global dHealth
attack = random.randint(5,50)
dHealth = dHealth - attack
print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
attack()
print(dHealth)但是还有另一种方法,那就是用函数返回一个值并将其赋值给dHealth。
代码:
import random
health = 100
dHealth = 1000
def attack(dHealth):
attack = random.randint(5,50)
dHealth = dHealth - attack
print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
return dHealth
dHealth = attack(dHealth) # Here, the returned value of dHealth after
# reduction is assigned to the global variable
# so no need to use global variables
print(dHealth) https://stackoverflow.com/questions/71628164
复制相似问题