1 >>> sequence=(1,2,None,4,None,5)
2 >>> total=0
3 >>> def sum(ss):
4 for value in sequence:
5 if value is None:
6 continue
7 total +=total
8 return(total)
9
10 >>> sum(sequence)
11 Traceback (most recent call last):
12 File "<pyshell#326>", line 1, in <module>
13 sum(sequence)
14 File "<pyshell#325>", line 5, in sum
15 total +=total
16 UnboundLocalError: local variable 'total' referenced before assignment
17 >>> def sum(ss):
18 for value in sequence:
19 if value is None:
20 continue
21 total +=value
22 return(total)
23
24 >>> sum(sequence)
25 Traceback (most recent call last):
26 File "<pyshell#329>", line 1, in <module>
27 sum(sequence)
28 File "<pyshell#328>", line 5, in sum
29 total +=value
30
31 UnboundLocalError: local variable 'total' referenced before assignment
32 >>> def sum(ss):
33 total=0
34 for value in sequence:
35 if value is None:
36 continue
37 total +=value
38 return(total)
39
40 >>> sum(sequence)
41 12
local variable 'total' referenced before assignment的中文意思是:局部变量在引用前要先赋值。也就是说,def定义的函数中的局部变量total要在函数内进行预定义,
定义为全局变量不可用。