You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python循环实现整数上下往复递增,模拟恒温器温度波动

问题根因分析
  • 作用域错误导致last_temp永久未更新:外层函数定义的last_temp,在内层increment函数里直接赋值会被Python识别为局部变量,不会修改外层的last_temp,导致外层last_temp永远停留在初始值69,所有判断逻辑完全错位。这也是为什么actual_temp在70的时候会回升到71——70始终大于69,每次都会触发升温判断,只有涨到71碰到max阈值才会减1回70,最终只能在两个值之间循环。
  • 初始等值场景无处理逻辑:当实际温度和last_temp相等时,现有判断分支不会触发任何温度调整,温度会直接停滞。
  • Thermostat类阈值未同步更新:调用set_the_temp修改设定温度后,max和min属性不会重新计算,阈值永远和初始设定温度绑定,后续修改设定温度会失效。
修复方案

1. 修复Thermostat类阈值同步问题

用属性装饰器实现阈值自动计算,不需要手动同步,修改设定温度后阈值会自动更新:

class Thermostat:
    def __init__(self, set_temp = 70, actual_temp = 70):
        self.set_temp = set_temp
        self.actual_temp = actual_temp

    # 用属性装饰器,每次读取时自动基于当前设定温度计算阈值
    @property
    def max(self):
        return self.set_temp + 1
    @property
    def min(self):
        return self.set_temp - 2

    def set_the_temp(self, x):
        self.set_temp = x

    def increment_temp(self, x):
        self.actual_temp += x

# 初始化恒温器
thermostat = Thermostat()

2. 修复循环逻辑

去掉冗余嵌套函数,改用方向变量控制温度升降,逻辑更清晰不易出错:

import time
from random import randint

def increment_temp():
    # 初始方向设为升温,也可根据需求随机初始方向
    direction = 1
    while True:
        # 碰到上边界就切换为降温,碰到下边界就切换为升温
        if thermostat.actual_temp >= thermostat.max:
            direction = -1
        elif thermostat.actual_temp <= thermostat.min:
            direction = 1
        
        # 执行温度调整
        last_temp = thermostat.actual_temp
        thermostat.increment_temp(direction)
        
        # 打印日志
        print("set temp: ", thermostat.set_temp)
        print("actual temp: ", thermostat.actual_temp)
        print("last temp:", last_temp)
        
        time.sleep(randint(2,10))

修复后温度会在[设定温度-2, 设定温度+1]的区间内持续往复波动,修改设定温度后阈值也会自动同步调整。

内容的提问来源于stack exchange,提问作者jumper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:27:02