我正在尝试为温度传感器编写代码。当我尝试执行代码时被卡在NameError上。我的问题是,有人知道我在做什么错吗?

码:

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


错误:

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

最佳答案

仅在热水功能中可访问变量摄氏。无法在其外部访问它。要解决此问题,您可以将打印移至热水功能中:

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


或者,您可以将热水返回摄氏温度:

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


尽管您可以使用global关键字使摄氏在任何地方都可以访问,但是通常对此并不满意。

10-08 00:34