UnboundLocalError:本地变量'slcount'在赋值前被引用
我正在尝试遍历从数据库中获取的结果,
在条件判断中,我检查某个条件,如果这个条件成立,我想要增加一个值。
for row in rows:
if row.LeavesApplied.type_id == "SICK_LEAVE" and row.Employee.leave_eligibility_id == 2:
global slcount
slcount+= 1
elif row.LeavesApplied.type_id == "CASUAL_LEAVE" and row.Employee.leave_eligibility_id == 2:
clcount += 1
elif row.LeavesApplied.type_id == "PRIVILEGED_LEAVE" and row.Employee.leave_eligibility_id == 2:
plcount += 1
但是我遇到了一个错误,提示是:
UnboundLocalError: local variable 'slcount' referenced before assignment
我也试着使用“global”关键字,但它显示了下面的错误。
NameError: global name 'slcount' is not defined
1 个回答
3
你在使用 plcount
之前没有给它赋值。
slcount = clcount = plcount = 0
for row in rows:
...
再多说一点:
Python 是一种动态类型的语言。
这意味着在 Python 中你可以这样做:
> foo = 12
> foo = 'aaa'
你看到了吗?我可以给一个变量赋任何类型的值。而在静态类型的语言中:
> int foo;
> foo = 12;
> foo = 'aaa'; // you can't do this!
不过,这并不意味着你可以在 Python 中这样做:
> foo = foo + 1 # you haven't assign a value to foo!