函数

时间:2018-04-20 05:28:57

标签: python

这很好用:

    import time

    def load():
        a = 0
        l = range(10000000)
        b = 100/len(l)
        start = time.time()
        for i in l:
            a += b
        end = time.time()
        print(end-start)

    load()

现在我希望我的函数使用a作为全局变量:

import time

a = 0

def f():
    global a
    a = 0

def load():
    l = range(10000000)
    b = 100/len(l)
    start = time.time()
    for i in l:
        a += b
    end = time.time()
    print(end-start)
f()
load()

但它会返回错误:UnboundLocalError: local variable 'a' referenced before assignment

编辑:

我在一个帖子中发现了这个并且它有效:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

但是我的功能有什么不同?

0 个答案:

没有答案