>>> total = 0
>>>
>>> def sum(arg1, arg2):
... total = arg1+arg2
... print 'inside the function total total : %s' % (total)
... return total
...
>>> sum(10, 20)
inside the function total total : 30
30
>>> print 'outside the function global total : %s' % (total)
outside the function global total : 0
>>>
>>> total = sum(10, 20)
inside the function total total : 30
>>> print 'outside the function global total : %s' % (total)
outside the function global total : 30
>>>
如果你想定义全局标量,应该是这样
>>> global total
>>> ......
注意:
>>> global total
>>> total
>>> def sum(arg1, arg2):
... total = ...
这三个total是完全不一样的三个变量
具体的区别请查看变量的作用范围,看完如果还不明白请继续提问。
全局变量定义错误,不是这样写的