全局变量的答案?

2024-09-28 17:19:02 发布

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

我是一个初学者编码,我有这个游戏,我正在做,但我的问题是,在我的游戏中,用户有点,他们可以在战斗中花费。它会根据你花了多少钱来更新积分变量

global Points
    Points = int(100)
def Combat():
    print('how much points would you spend(higher points = higher chance of winning')
    a9 = int(input('>'))
    Points = int(Points)- int(a9)
    global Points
    print('You have ',Points,' points')

但由于某种原因,它不会改变全局点变量,有答案吗? 这有答案吗? 还是悬而未决


Tags: 答案用户游戏编码defglobalpointsint
1条回答
网友
1楼 · 发布于 2024-09-28 17:19:02

在函数中为global Points赋值之前,需要先输入Points,否则使用的是函数本地的Points,并隐藏要使用的全局点:

Points = 100

def Combat():
    print('how much points would you spend(higher points = higher chance of winning')
    a9 = int(input('>'))
    global Points
    Points = Points - int(a9)
    print('You have ',Points,' points')

此外,您不需要最初使用global Points,因为函数外部自动是全局范围

相关问题 更多 >