小编sss*_*ure的帖子

UnboundLocalError:赋值前引用的局部变量“sum”

代码1:

# coding:utf-8

sum = 5

def add(x, y):
    print sum
    sum = x + y

if __name__ == '__main__':
    add(7, 8)
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,出现以下错误:

ssspure:python ssspure$ python test.py
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    add(7, 8)
  File "test.py", line 6, in add
    print sum
UnboundLocalError: local variable 'sum' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

代码2:

ssspure:python ssspure$ python test.py
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    add(7, 8)
  File "test.py", line 6, in add
    print …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

4
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×1

python-2.7 ×1