UnboundLocalError:分配Python之前引用的本地变量[duplicate]

时间:2022-04-02 22:48:43

This question already has an answer here:

这个问题已经有了答案:

I've been having trouble with the "def" function. I know this question has already been asked, but the answer didn't satisfy me and I didn't see how to apply it to my code. I'm trying to make the the popular game 2048 in Python. Basically, when I define the function that makes the entire board move left, it bites me with the error: UnboundLocalError: local variable referenced before assignment. It seems that I have to define the variables "bone" and "btwo" in somewhere that isn't, like, global. But I am yet to figure out how to get that working. Setting parameters in my moveleft() function isn't working, e.g moveleft(bone,btwo). So I'm at my wit's end.

我在“def”函数上遇到了麻烦。我知道已经有人问过这个问题了,但是我对这个问题的答案并不满意,我也不知道如何将它应用到我的代码中。我正在尝试用Python制作流行的游戏2048。基本上,当我定义使整个黑板向左移动的函数时,它会提示我一个错误:UnboundLocalError:赋值前引用的本地变量。似乎我必须在某个不像全局变量的地方定义“bone”和“btwo”。但我还没想好如何让它发挥作用。在我的moveleft()函数中设置参数不起作用,e。btwo g moveleft(骨)。我已经绞尽脑汁了。

Now, I'll include the entire code, all commented up, but the part I think has the problem is where I define the function moveleft(). Also, if there are any outstanding stupid bits of code, please tell me. Also, try and keep it simple, I'm pretty rubbish with programming and its associated phrases and terms. This is only my 3rd attempt at a code.

现在,我将包含整个代码,全部注释完毕,但是我认为有问题的部分是我定义moveleft()函数的地方。此外,如果有任何突出的愚蠢的代码片段,请告诉我。另外,尽量保持简单,我对编程及其相关的短语和术语一窍不通。这是我第三次尝试编码。

I realise I'm asking a lot, but I would really, really, appreciate help with this.

我知道我要求很多,但我真的非常非常感谢你的帮助。

Code: http://pastebin.ca/2824228

代码:http://pastebin.ca/2824228

Minimized version:

最小化版本:

bone, btwo = 1, 2

def move_left():
    if bone == 1: print("bone is 1")
    if btwo == 2: print("btwo is 2")

    btwo = 3 
    bone = 2 

move_left()

1 个解决方案

#1


3  

If you are writing to a global variable inside a function, then you need to explicitly say that you are referring to a global variable. So put this as the first line in your function:

如果要在函数中写入全局变量,那么需要明确地说,您指的是全局变量。把它作为函数的第一行

global bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine

And, why don't you use a list instead of defining 9 variables?

为什么不使用列表而不是定义9个变量呢?

#1


3  

If you are writing to a global variable inside a function, then you need to explicitly say that you are referring to a global variable. So put this as the first line in your function:

如果要在函数中写入全局变量,那么需要明确地说,您指的是全局变量。把它作为函数的第一行

global bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine

And, why don't you use a list instead of defining 9 variables?

为什么不使用列表而不是定义9个变量呢?