获取循环中的第二个值

2024-05-20 19:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在写一个电报机器人从树莓皮上的enviro+phat获取实时数据。。。你知道吗

运行内置示例时,它将始终打印以下内容:

The current tempurature is 21.70818430223153 *C 

The current pressure is  700.2708792437015hPa

The Current Humidty is 84.54408663293306 %

在while循环的下一次打印中,它将为您提供正确的环境数据。为了解决这个问题,我只需要获取第二组数据,而不是第一组数据。你知道吗

我试过在while循环中缩进变量,但这在bot中不起作用。你知道吗

下面是在bot中工作的内容,但是每次获取天气状态时,都会获取与上面发布的相同的值。你知道吗

def weather(bot, update):
    chat_id = update.message.chat_id
    temp = bme280.get_temperature()
    pressure = bme280.get_pressure()
    humidity = bme280.get_humidity()
    current_temp = "The current tempurature is " + str(temp)  + " *C " + "\nThe current pressure is  " +  str(pressure) + "hPa" + "\nThe Current Humidty is " + str(humidity) + " %"
    bot.send_message(chat_id=chat_id, text=current_temp)

while循环仍然会带来相同的值,而不是示例循环中的下一个值。你知道吗

任何帮助都将不胜感激


Tags: the数据id示例getisbotchat
2条回答

在过去的几天里,我完成了这项工作,这花了我一点时间,因为我仍然在学习python,但之前是工作代码:

while True: 
    if counter < 2:
        temperature = bme280.get_temperature()
        pressure = bme280.get_pressure()
        humidity = bme280.get_humidity()
        counter = counter + 1
        time.sleep(1)
    else:
        print("""Temperature: {:05.2f} *C
    Pressure: {:05.2f} hPa
    Relative humidity: {:05.2f} %
    """.format(temperature, pressure, humidity))
        break

听起来像是第一个请求或第一个循环初始化bot并返回默认值,然后得到实际值。你知道吗

也许这两种策略中的一种可行:

1.) Send a single request first and ignore the result, thereafter do a while loop
2.) Initialise a counter before the while loop and if counter = 1 then ignore results and loop

更多的代码可能有助于缩小答案的范围。你知道吗

相关问题 更多 >