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

Python初学者:while循环调用天气API重复输出旧数据求助

问题分析与修复方案

你的代码主要有三个问题导致后续查询重复首次数据:

  • 首次查询的temp、temp_max变量只赋值一次,后续循环没更新这些变量,输出自然不会变
  • while True循环后面的请求和输出代码根本跑不到,循环会一直卡着
  • 没做输入9退出的逻辑

下面是修正后的完整代码:

import requests

base_url = "sampleurl"
appid = "1a2b3c4d5e6f"

while True:
    city = input("Enter a zip code or city, or enter 9 to end the program: ")
    # 处理退出条件
    if city == "9":
        print("程序结束")
        break
    
    # 构造请求URL
    url = f"{base_url}?q={city}&units=imperial&APPID={appid}"
    print(f"请求URL: {url}\n")
    
    # 发起请求并解析数据
    try:
        response = requests.get(url)
        response.raise_for_status()  # 捕获HTTP请求错误
        weather_data = response.json()
        
        # 提取并输出天气数据
        temp = weather_data["main"]["temp"]
        temp_max = weather_data["main"]["temp_max"]
        print(f"当前温度: {temp}")
        print(f"最高温度: {temp_max}\n")
    except Exception as e:
        print(f"查询失败: {str(e)}\n")

关键修改说明:

  • 把所有查询逻辑放进while True循环里,每次输入新城市都会重新发起请求、解析数据、更新温度变量
  • 添加了if city == "9": break的退出逻辑,符合需求
  • 加了异常处理,避免输入无效城市或请求出错导致程序崩溃
  • 去掉了冗余的重复代码,让逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:09:12