[英]How do I edit a global variable within a function
我是 python 的新手,我正在尝试制作一个基于文本的小型游戏,我列出了玩家的健康状况,当我尝试在 function 中编辑变量时,它不会更改全局变量,并且何时我尝试使用全局命令将其定义为全局变量它说参数已经是全局变量并且返回也不起作用?
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 到 go 到 995 到 950 之间的数字
最好的解决方案是不要将其用作全局变量。 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
的被攻击的怪物命名。
因此,您需要在 function 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)
但是还有一种方法,就是返回一个function的值赋值给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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.