Reputation: 53
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
Upvotes: 1
Views: 3647
Reputation: 77837
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.
Upvotes: 1
Reputation: 875
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.
Upvotes: 2