This question already has an answer here:
这个问题已经有了答案:
- Python variable scope error 10 answers
- Python变量范围错误10答案。
I'm having an issue with variable and function. Here is a simple code:
我有一个变量和函数的问题。这里有一个简单的代码:
r = 0
list = ['apple','lime','orange']
def list_list(x):
for i in x:
r +=1
print r
list_list(list)
Error:
UnboundLocalError: local variable 'r' referenced before assignment
I know it must be something simple. I started to do my script using functions instead straight code.
我知道这一定很简单。我开始使用函数而不是直接代码来执行脚本。
3 个解决方案
#1
1
You should rewrite your function to take r
as an argument if you want to define it outside of your function:
如果你想把r定义在函数之外,你应该重写你的函数把r当作一个参数:
def my_func(some_list, r=0):
# do some stuff
Basically, you have a problem with scope. If you need r outside of the function, just return it's value in a tuple:
基本上,你有一个范围的问题。如果你需要函数外的r,只需返回一个元组中的值:
def my_func(some_list, r=0):
# do some stuff
return new_list, r
my_list = [1,2,3,4,5]
different_list, my_outside_r = my_func(some_list, 0)
#2
2
The r
within the function isn't the same as the one outside the function, so it hasn't been set yet.
函数内的r与函数外面的r不一样,所以它还没有被设置。
#3
1
You shoudld put r = 0
inside the function. But if you want the length of the list just use len(list)
你应该把r = 0放在函数里面。但是如果你想要列表的长度就用len(list)
Also try to avoid naming variables same as builtin names like list.
也要尽量避免使用与构建名称相同的命名变量。
#1
1
You should rewrite your function to take r
as an argument if you want to define it outside of your function:
如果你想把r定义在函数之外,你应该重写你的函数把r当作一个参数:
def my_func(some_list, r=0):
# do some stuff
Basically, you have a problem with scope. If you need r outside of the function, just return it's value in a tuple:
基本上,你有一个范围的问题。如果你需要函数外的r,只需返回一个元组中的值:
def my_func(some_list, r=0):
# do some stuff
return new_list, r
my_list = [1,2,3,4,5]
different_list, my_outside_r = my_func(some_list, 0)
#2
2
The r
within the function isn't the same as the one outside the function, so it hasn't been set yet.
函数内的r与函数外面的r不一样,所以它还没有被设置。
#3
1
You shoudld put r = 0
inside the function. But if you want the length of the list just use len(list)
你应该把r = 0放在函数里面。但是如果你想要列表的长度就用len(list)
Also try to avoid naming variables same as builtin names like list.
也要尽量避免使用与构建名称相同的命名变量。