1

I'm trying to make code for my temperature sensor. Been stuck on a NameError when I try to execute the code. My question is, does anyone have a clue what I am doing wrong?

Code:

import datetime
from sense_hat import SenseHat

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)

result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]

while __name__ == '__main__':
    Hotwater()

Error:

Traceback (most recent call last):
    file "/home/pi/Web_test.py", line 9 in <module>
       results= 'temp. C' + str(celcius)
NameError: name 'celcius' is not defined
Avery
  • 2,270
  • 4
  • 33
  • 35
  • 1
    `NameError: name 'celcius' is not defined` means just what it says ... `celcius` is not defined at the point where you are trying to use it. – Tony Tuttle Feb 15 '18 at 18:05

2 Answers2

2

The variable Celsius is only accessible in the hotwater function. It cannot be accessed outside of it. To fix the issue, you could move the printing into the hotwater function:

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)
    result = 'temp. C' + str(celcius)
    print(result)
    result_list = [(datetime.datetime.now(), celcius)]

hotwater()

Or, you could have hotwater return celsius:

def hotwater():
    sense = SenseHat()
    sense.clear()
    celcius = round(sense.get_temperature(), 1)
    return celcius

celcius= hotwater()
result = 'temp. C' + str(celcius)
print(result)
result_list = [(datetime.datetime.now(), celcius)]

Although you could use the global keyword to make celsius accessible everywhere, that is generally frowned upon.

Sam Craig
  • 875
  • 5
  • 16
1

Your function fails to returned the value to the main program. Variable celcius[sic] is local to the function. Also, you've failed to invoke the function where you try to use the value.

Follow the examples in your learning materials: call the function, return the value to the main program, and save or use it as needed:

def hotwater():
    sense = SenseHat()
    sense.clear()
    return round(sense.get_temperature(), 1)


if __name__ == '__main__':
    while True:
        celsius = hotwater()
        result = 'temp. C' + str(celcius)
        print(result)
        result_list = [(datetime.datetime.now(), celcius)]

I'm not sure what plans you have for result_list, but I think you'll need to update the code above.

Prune
  • 76,765
  • 14
  • 60
  • 81