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

Python天气提示程序运行中途终止问题排查求助

问题原因与解决方案

问题根源

程序本身存在逻辑错误,导致特定输入下陷入死循环,表现为"中途停止":

  • 当rain='yes'且wind='no'时,wind对应的while循环条件wind != 'yes'成立,但循环体内的if wind != 'no'条件不满足(此时wind是no),循环体代码完全不执行,程序卡在这个循环里无法继续向下运行。
  • 同理,rain的while循环也有相同问题:如果用户输入no,循环条件rain != 'yes'成立,但if rain != 'no'不满足,同样会陷入死循环。

修正后的代码

将输入验证逻辑改为只要输入不是yes或no就重新提示,确保输入合法后再继续执行:

# 验证rain的输入
rain = input('Is it raining? yes/no ').lower()
while rain not in ['yes', 'no']:
    rain = input('Is it raining? yes/no ').lower()
print()

# 验证wind的输入
wind = input('Is it windy? yes/no ').lower()
while wind not in ['yes', 'no']:
    wind = input('Is it windy? yes/no ').lower()
print()

# 输出建议
if rain == 'yes' and wind == 'yes':
    print('Wear a raincoat. ')
elif rain == 'yes':
    print('Bring an umbrella. ')
elif wind == 'yes':
    print('Wear a jersey. ')
else:
    print('Wear a shirt. ')
print(':)')

修正说明

  • 简化输入处理:将str(input())改为input()(input()本身返回字符串),并直接链式调用.lower()
  • 优化循环条件:用rain not in ['yes', 'no']直接判断输入是否合法,只要不合法就重复提示,避免原逻辑中的死循环问题
  • 代码结构更简洁,逻辑更清晰,能覆盖所有合法输入场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:40:29