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
1
  • 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. Commented Feb 15, 2018 at 18:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.