以下代码在Python 2.5和3.0中按预期工作:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值a和b被正确地打印.这让我感到困惑,原因有两个:
为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?
为什么变量a和b打印符合预期,同时c引发错误?
我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c
有人可以解释一下这种行为吗?
以下代码给出了错误UnboundLocalError: local variable 'Var1' referenced before assignment:
Var1 = 1
Var2 = 0
def function():
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?谢谢你的帮助!
对于以下Python 2.7代码:
#!/usr/bin/python
def funcA():
print "funcA"
c = 0
def funcB():
c += 3
print "funcB", c
def funcC():
print "funcC", c
print "c", c
funcB()
c += 2
funcC()
c += 2
funcB()
c += 2
funcC()
print "end"
funcA()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "./a.py", line 9, in funcB
c += 3
UnboundLocalError: local variable 'c' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
但是,当我注释掉该行c += 3中funcB,我得到以下的输出:
funcA
c 0
funcB 0
funcC 2
funcB 4
funcC 6
end
Run Code Online (Sandbox Code Playgroud)
c在 …
我首先要说的是:我知道这个问题被很多人问到。我已经阅读了其他答案,并排除了:
我没有使用 += 进行作业;
我尝试显式分配函数中的每个变量,以确保它们不为空,以防函数执行的其他工作失败;
它们不是全局变量,我也不希望它们成为全局变量——它们只是我用来计算最终返回的内容的内部变量。
## Gets the data from external website - refreshes whenever the programme is called.
## Urllib2 required module
## csv to make life easier handling the data
import urllib2
import csv
import sys
import math
# import sqlite3 #don't need this just now, will probably run Django with MySQL when it comes to it
# import MySQLdb Likewise, don't need this just now.
#python3
import atexit
from time import time
from datetime …Run Code Online (Sandbox Code Playgroud)