如何在Python中定义变量后更改变量

时间:2022-11-05 19:41:17

I'm trying to add or subtract from a defined variable, but I can't figure out how to overwrite the old value with the new one.

我正在尝试添加或减去已定义的变量,但我无法弄清楚如何使用新值覆盖旧值。

a = 15def test():    a = a +10    print ( a )test()

Error message:

Traceback (most recent call last):  File "test.py", line 7, in <module>    test()  File "test.py", line 4, in test    a = a +10UnboundLocalError: local variable 'a' referenced before assignment

6 个解决方案

#1


23  

The error that you get when you try to run your code is:

尝试运行代码时出现的错误是:

UnboundLocalError: local variable 'a' referenced before assignment

… which, on the face of it, seems strange: after all, the first statement in the code above (a = 15) is an assignment. So, what's going on?

......从表面上看,它看起来很奇怪:毕竟,上面代码中的第一个语句(a = 15)是一个赋值。发生什么了?

Actually, there are two distinct things happening, and neither of them are obvious unless you already know about them.

实际上,发生了两件截然不同的事情,除非你已经了解它们,否则它们都不明显。

First of all, you actually have two different variables:

首先,您实际上有两个不同的变量:

  • The a in your first line is a global variable (so called because it exists in the global scope, outside of any function definitions).

    第一行中的a是一个全局变量(因为它存在于全局范围内,在任何函数定义之外)。

  • The a in the other lines is a local variable, meaning that it only exists inside your test() function.

    其他行中的a是局部变量,这意味着它只存在于test()函数中。

These two variables are completely unrelated to each other, even though they have the same name.

这两个变量彼此完全无关,即使它们具有相同的名称。

A variable is local to a function if there's a statement assigning to it inside that function - for instance, your a = a +10 line.

变量是函数的局部变量,如果在该函数中有一个语句分配给它 - 例如,你的a = a +10行。

Even so, the error still looks strange - after all, the very first thing you do inside test() is assign to a, so how can it be referenced beforehand?

即便如此,错误仍然看起来很奇怪 - 毕竟,你在test()中做的第一件事是分配给a,那么如何才能事先引用呢?

The answer is that, in an assignment statement, Python evaluates everything on the right hand side of the = sign before assigning it to the name on the left hand side – so even though the assignment is written first in your code, a gets referenced first in that right hand side: a +10.

答案是,在赋值语句中,Python会在将符号分配到左侧的名称之前评估=符号右侧的所有内容 - 因此,即使首先在代码中编写赋值,也会首先引用在那个右手边:a +10。

There are two ways you can get around this. The first is to tell Python that you really want the a inside test() to be the same a in the global scope:

有两种方法可以解决这个问题。第一个是告诉Python你真的希望内部test()在全局范围内是相同的a:

def test():    global a    a = a + 10    print(a)

This will work, but it's a pretty bad way to write programs. Altering global variables inside functions gets hard to manage really quickly, because you usually have lots of functions, and none of them can ever be sure that another one isn't messing with the global variable in some way they aren't expecting.

这可行,但编写程序是一种非常糟糕的方式。改变函数内部的全局变量很难快速管理,因为你通常有很多函数,而且没有人能够确定另一个函数没有以某种他们不期望的方式搞乱全局变量。

A better way is to pass variables as arguments to functions, like this:

更好的方法是将变量作为参数传递给函数,如下所示:

a = 15def test(x):    x = x + 10    print(x)test(a)

Notice that the name doesn't have to be the same - your new definition of test() just says that it accepts a value, and then does something with it. You can pass in anything you like – it could be a, or the number 7, or something else. In fact, your code will always be easier to understand if you try to avoid having variables with the same name in different scopes.

请注意,名称不必相同 - 您对test()的新定义只是说它接受一个值,然后用它做一些事情。你可以传递你喜欢的任何东西 - 它可以是a,或7,或其他东西。实际上,如果您尝试避免在不同范围内使用相同名称的变量,则代码将始终更容易理解。

If you play with the code above, you'll notice something interesting:

如果你玩上面的代码,你会发现一些有趣的东西:

>>> a = 15>>> test(a)25>>> a15

a didn't change! That's because although you passed it into test() and it got assigned to x, it was then x that got changed, leaving the original a alone.

......一个没改变!那是因为虽然你把它传递给了test()并且它被分配给了x,然后它被改变了x,原来是一个人。

If you want to actually change a, you need to return your modified x from the function, and then reassign it back to a on the outside:

如果您想要实际更改a,则需要从函数返回修改后的x,然后将其重新分配给外部:

>>> a = 15>>> >>> def test(x):...     x = x + 10...     print(x)...     return x... >>> a = test(a)25>>> a25

#2


2  

You're modifying a variable a created in the scope of the function test(). If you want the outter a to be modified you could do:

您正在修改在函数test()范围内创建的变量。如果你想要修改outter a,你可以这样做:

a = 15def test():    global a    a = a + 1    print(a)test()

#3


2  

I would do it this way:

我会这样做:

def test(a):    a = a +10    return aprint(test(15))

Note that in the version hereby proposed there are some things differing from yours.

请注意,在此提出的版本中,有一些与您的不同。

First, what I wrote down would create a function that has, as an input, the value a (in this case set to 15 when we call the function -already defined in the last line-), then assigns to the object a the value a (which was 15) plus 10, then returns a (which has been modified and now is 25) and, finally, prints a out thanks to the last line of code:

首先,我写下来的内容将创建一个函数,作为输入,值a(在这种情况下,当我们调用函数 - 在最后一行中定义时设置为15),然后为对象分配值a(15)加10,然后返回a(已被修改,现在是25),最后,由于最后一行代码打印出来:

print(test(15))

Note that what you did wasn't actually a pure function, so to speak. Usually we want functions to get an input value (or several) and return an input value (or several). In your case you had an input value that was actually empty and no output value (as you didn't use return). Besides, you tried to write this input a outside the function (which, when you called it by saying test(a) the value a was not loaded an gave you the error -i.e. in the eyes of the computer it was "empty").

请注意,你所做的并不是一个纯粹的功能,可以这么说。通常我们希望函数获取输入值(或几个)并返回一个输入值(或几个)。在你的情况下,你有一个实际上是空的输入值,没有输出值(因为你没有使用return)。此外,你试图把这个输入写在函数外面(当你通过说test(a)没有加载的值来调用它时,给你的错误 - 在计算机眼中它是“空的”) 。

Furthermore, I would encourage you to get used to writing return within the function and then using a print when you call it (just like I wrote in the last coding line: print(test(15))) instead of using it inside the function. It is better to use print only when you call the function and want to see what the function is actually doing.

此外,我鼓励你习惯在函数内写回,然后在调用它时使用打印(就像我在上一个编码行中写的那样:print(test(15)))而不是在函数内部使用它。最好只在调用函数时使用print,并希望查看函数实际执行的操作。

At least, this is the way they showed me in basic programming lessons. This can be justified as follows: if you are using the return within the function, the function will give you a value that can be later used in other functions (i.e. the function returns something you can work with). Otherwise, you would only get a number displayed on screen with a print, but the computer could not further work with it.

至少,这是他们在基础编程课程中向我展示的方式。这可以证明如下:如果你在函数中使用返回,该函数将给你一个值,以后可以在其他函数中使用(即函数返回你可以使用的东西)。否则,您只能在屏幕上显示带有打印件的数字,但计算机无法继续使用它。

P.S. You could do the same doing this:

附:你也可以这样做:

def test(a):    a +=10          return aprint(test(15))

#4


0  

Scope of the variable is local to the block unless defined explicitly using keyword global. There is other way to access the global variable local to a function using globals function

除非使用关键字global明确定义,否则变量的范围是块的本地。还有其他方法可以使用globals函数访问函数的局部全局变量

a = 15def test():    a = globals()['a']    a += 10    print ( a )test()

Above example will print 25 while keeping the global value intact i.e 15.

以上示例将打印25,同时保持全局值不变,即15。

#5


-3  

# All the mumbo jumbo aside, here is an experiment # to illustrate why this is something useful # in the language of Python:a = 15    # This could be read-only, should check docsdef test_1():    b = a + 10    # It is perfectly ok to use 'a'    print(b)def test_2():    a = a + 10    # Refrain from attempting to change 'a'    print(a)test_1()    # No errortest_2()    # UnboundLocalError: ...

#6


-5  

Your error has nothing to do with is being already defined…A variable is only valid inside it's so called scope: If you create a variable in a function it is only defined in this function.

您的错误与已定义无关...变量仅在其所谓的范围内有效:如果在函数中创建变量,则仅在此函数中定义。

def test():   x=17   print(x) # returns 17test()print(x) # results in an error.

#1


23  

The error that you get when you try to run your code is:

尝试运行代码时出现的错误是:

UnboundLocalError: local variable 'a' referenced before assignment

… which, on the face of it, seems strange: after all, the first statement in the code above (a = 15) is an assignment. So, what's going on?

......从表面上看,它看起来很奇怪:毕竟,上面代码中的第一个语句(a = 15)是一个赋值。发生什么了?

Actually, there are two distinct things happening, and neither of them are obvious unless you already know about them.

实际上,发生了两件截然不同的事情,除非你已经了解它们,否则它们都不明显。

First of all, you actually have two different variables:

首先,您实际上有两个不同的变量:

  • The a in your first line is a global variable (so called because it exists in the global scope, outside of any function definitions).

    第一行中的a是一个全局变量(因为它存在于全局范围内,在任何函数定义之外)。

  • The a in the other lines is a local variable, meaning that it only exists inside your test() function.

    其他行中的a是局部变量,这意味着它只存在于test()函数中。

These two variables are completely unrelated to each other, even though they have the same name.

这两个变量彼此完全无关,即使它们具有相同的名称。

A variable is local to a function if there's a statement assigning to it inside that function - for instance, your a = a +10 line.

变量是函数的局部变量,如果在该函数中有一个语句分配给它 - 例如,你的a = a +10行。

Even so, the error still looks strange - after all, the very first thing you do inside test() is assign to a, so how can it be referenced beforehand?

即便如此,错误仍然看起来很奇怪 - 毕竟,你在test()中做的第一件事是分配给a,那么如何才能事先引用呢?

The answer is that, in an assignment statement, Python evaluates everything on the right hand side of the = sign before assigning it to the name on the left hand side – so even though the assignment is written first in your code, a gets referenced first in that right hand side: a +10.

答案是,在赋值语句中,Python会在将符号分配到左侧的名称之前评估=符号右侧的所有内容 - 因此,即使首先在代码中编写赋值,也会首先引用在那个右手边:a +10。

There are two ways you can get around this. The first is to tell Python that you really want the a inside test() to be the same a in the global scope:

有两种方法可以解决这个问题。第一个是告诉Python你真的希望内部test()在全局范围内是相同的a:

def test():    global a    a = a + 10    print(a)

This will work, but it's a pretty bad way to write programs. Altering global variables inside functions gets hard to manage really quickly, because you usually have lots of functions, and none of them can ever be sure that another one isn't messing with the global variable in some way they aren't expecting.

这可行,但编写程序是一种非常糟糕的方式。改变函数内部的全局变量很难快速管理,因为你通常有很多函数,而且没有人能够确定另一个函数没有以某种他们不期望的方式搞乱全局变量。

A better way is to pass variables as arguments to functions, like this:

更好的方法是将变量作为参数传递给函数,如下所示:

a = 15def test(x):    x = x + 10    print(x)test(a)

Notice that the name doesn't have to be the same - your new definition of test() just says that it accepts a value, and then does something with it. You can pass in anything you like – it could be a, or the number 7, or something else. In fact, your code will always be easier to understand if you try to avoid having variables with the same name in different scopes.

请注意,名称不必相同 - 您对test()的新定义只是说它接受一个值,然后用它做一些事情。你可以传递你喜欢的任何东西 - 它可以是a,或7,或其他东西。实际上,如果您尝试避免在不同范围内使用相同名称的变量,则代码将始终更容易理解。

If you play with the code above, you'll notice something interesting:

如果你玩上面的代码,你会发现一些有趣的东西:

>>> a = 15>>> test(a)25>>> a15

a didn't change! That's because although you passed it into test() and it got assigned to x, it was then x that got changed, leaving the original a alone.

......一个没改变!那是因为虽然你把它传递给了test()并且它被分配给了x,然后它被改变了x,原来是一个人。

If you want to actually change a, you need to return your modified x from the function, and then reassign it back to a on the outside:

如果您想要实际更改a,则需要从函数返回修改后的x,然后将其重新分配给外部:

>>> a = 15>>> >>> def test(x):...     x = x + 10...     print(x)...     return x... >>> a = test(a)25>>> a25

#2


2  

You're modifying a variable a created in the scope of the function test(). If you want the outter a to be modified you could do:

您正在修改在函数test()范围内创建的变量。如果你想要修改outter a,你可以这样做:

a = 15def test():    global a    a = a + 1    print(a)test()

#3


2  

I would do it this way:

我会这样做:

def test(a):    a = a +10    return aprint(test(15))

Note that in the version hereby proposed there are some things differing from yours.

请注意,在此提出的版本中,有一些与您的不同。

First, what I wrote down would create a function that has, as an input, the value a (in this case set to 15 when we call the function -already defined in the last line-), then assigns to the object a the value a (which was 15) plus 10, then returns a (which has been modified and now is 25) and, finally, prints a out thanks to the last line of code:

首先,我写下来的内容将创建一个函数,作为输入,值a(在这种情况下,当我们调用函数 - 在最后一行中定义时设置为15),然后为对象分配值a(15)加10,然后返回a(已被修改,现在是25),最后,由于最后一行代码打印出来:

print(test(15))

Note that what you did wasn't actually a pure function, so to speak. Usually we want functions to get an input value (or several) and return an input value (or several). In your case you had an input value that was actually empty and no output value (as you didn't use return). Besides, you tried to write this input a outside the function (which, when you called it by saying test(a) the value a was not loaded an gave you the error -i.e. in the eyes of the computer it was "empty").

请注意,你所做的并不是一个纯粹的功能,可以这么说。通常我们希望函数获取输入值(或几个)并返回一个输入值(或几个)。在你的情况下,你有一个实际上是空的输入值,没有输出值(因为你没有使用return)。此外,你试图把这个输入写在函数外面(当你通过说test(a)没有加载的值来调用它时,给你的错误 - 在计算机眼中它是“空的”) 。

Furthermore, I would encourage you to get used to writing return within the function and then using a print when you call it (just like I wrote in the last coding line: print(test(15))) instead of using it inside the function. It is better to use print only when you call the function and want to see what the function is actually doing.

此外,我鼓励你习惯在函数内写回,然后在调用它时使用打印(就像我在上一个编码行中写的那样:print(test(15)))而不是在函数内部使用它。最好只在调用函数时使用print,并希望查看函数实际执行的操作。

At least, this is the way they showed me in basic programming lessons. This can be justified as follows: if you are using the return within the function, the function will give you a value that can be later used in other functions (i.e. the function returns something you can work with). Otherwise, you would only get a number displayed on screen with a print, but the computer could not further work with it.

至少,这是他们在基础编程课程中向我展示的方式。这可以证明如下:如果你在函数中使用返回,该函数将给你一个值,以后可以在其他函数中使用(即函数返回你可以使用的东西)。否则,您只能在屏幕上显示带有打印件的数字,但计算机无法继续使用它。

P.S. You could do the same doing this:

附:你也可以这样做:

def test(a):    a +=10          return aprint(test(15))

#4


0  

Scope of the variable is local to the block unless defined explicitly using keyword global. There is other way to access the global variable local to a function using globals function

除非使用关键字global明确定义,否则变量的范围是块的本地。还有其他方法可以使用globals函数访问函数的局部全局变量

a = 15def test():    a = globals()['a']    a += 10    print ( a )test()

Above example will print 25 while keeping the global value intact i.e 15.

以上示例将打印25,同时保持全局值不变,即15。

#5


-3  

# All the mumbo jumbo aside, here is an experiment # to illustrate why this is something useful # in the language of Python:a = 15    # This could be read-only, should check docsdef test_1():    b = a + 10    # It is perfectly ok to use 'a'    print(b)def test_2():    a = a + 10    # Refrain from attempting to change 'a'    print(a)test_1()    # No errortest_2()    # UnboundLocalError: ...

#6


-5  

Your error has nothing to do with is being already defined…A variable is only valid inside it's so called scope: If you create a variable in a function it is only defined in this function.

您的错误与已定义无关...变量仅在其所谓的范围内有效:如果在函数中创建变量,则仅在此函数中定义。

def test():   x=17   print(x) # returns 17test()print(x) # results in an error.