0

I am splitting up my code into separate files, but have a problems with variables within the sub files (I am sure it's something simple, but cannot work out what is wrong.

When I run the code I get an "UnboundLocalError: local variable 'avglightlevel' referenced before assignment" error.

I thought the variables would be local to the sub file, I have tried using global variables in each file and still cannot it working.

How do I a variable in the sub file to keep a running total of the avg values?

#main.py
import datacalc

datacalc.init(0)


#Read sensors & process the data
datacalc.complielightlevel(lightlevel)

# delay for 10 seconds and keep repeat 

======================================================
#datacalc.py
def init(avg):

      avglightlevel = 0 
      avgCO2level = 0
      avgtemperaturelevel = 0

#================================================   
def complielightlevel(lightlevel):
    if(lightlevel > 0):
          avglightlevel = avglightlevel + lightlevel
Brendon Shaw
  • 141
  • 13

1 Answers1

0

It appears that avglightlevel needs to be accessed with respect to the datacalc module. Something like this might work:

First, in datacalc.py:

def init(avg):
    global avglightlevel # Declares that `avglightlevel` should be in the global scope.
    global avgCO2level
    global avgtemperaturelevel
    avglightlevel = 0 
    avgCO2level = 0
    avgtemperaturelevel = 0

Then, inside of main.py:

def complielightlevel(lightlevel):
    if(lightlevel > 0):
        # We modify the `avglightlevel` in the `datacalc` module.
        datacalc.avglightlevel = datacalc.avglightlevel + lightlevel

Hope this helps!