0

This works fine:

    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()

Now I want my function to use a as a global variable:

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()

But it returns an Error: UnboundLocalError: local variable 'a' referenced before assignment

Edit:

I found this in a thread and it works:

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

But what is the difference to my function?

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
  • 1
    there is an obvious difference in how you use the global `a` in `f` and in `load` in your second code – FlyingTeller Apr 20 '18 at 05:31
  • I know that. But how do I make it work? – Artur Müller Romanov Apr 20 '18 at 05:35
  • Oops. Just deleted my comment :) I'll repost it – PeptideWitch Apr 20 '18 at 05:45
  • @ PeptideWitch thanks, `load(a)` solved the problem. – Artur Müller Romanov Apr 20 '18 at 05:47
  • 1
    So one way around this is to pass a into the function like this: 'load(a)'. Then in the function header put in 'def load(a):'. This will make a local version of a for you to play with inside the context of the function. Just to add - it doesn't change global 'a'. – PeptideWitch Apr 20 '18 at 05:47
  • 1) The difference is `print_globvar` is only **reading** `globvar`. Your code is reading and writing, since `a += b` is `a = a + b`... since you are going to assign (left `a`) to it, python automatically will assume a to be a local variable, but then when you try to read it (right `a`) there is no such `a`. – WillMonge Apr 20 '18 at 06:02
  • 2) You could include a `global a` at the start of your `load` function and it should work properly. – WillMonge Apr 20 '18 at 06:03

0 Answers0