UnboundLocalError。为什么会这样?

时间:2014-03-04 20:13:42

标签: python list for-loop sqlite

c.execute("SELECT * FROM Student, Behaviour")
data = c.fetchall() #'data' is a tuple and cannot be altered
l = []
for i in data: #for individual records in the whole database do:
    record = str(i)
    record = record.replace("u'","")
    record = record.replace("'", "")
    record = record.replace('"', '')
    record = record.replace("(","")
    record = record.replace(")", "")
    Formattedrecord = record.replace(","," -")
l.append(Formattedrecord)

返回错误:UnboundLocalError:赋值前引用的局部变量'Formattedrecord' 但我不明白为什么,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

小心缩进:

c.execute("SELECT * FROM Student, Behaviour")
data = c.fetchall() #'data' is a tuple and cannot be altered
l = []
for i in data: #for individual records in the whole database do:
    record = str(i)
    record = record.replace("u'","")
    record = record.replace("'", "")
    record = record.replace('"', '')
    record = record.replace("(","")
    record = record.replace(")", "")
    Formattedrecord = record.replace(","," -")
    l.append(Formattedrecord) # this should be part of the for loop