19.简单项目:天气查询脚本

19.简单项目:天气查询脚本

欢迎来到《10天学会Python》第10天!今天我们将综合运用所学知识,完成一个完整的项目——天气查询脚本。

《10天学会Python》的代码看

核心概念

项目开发就像盖房子

  • 需求分析:确定要做什么(如查询天气)
  • 设计:规划代码结构和功能模块
  • 编码:按设计编写代码
  • 测试:验证功能是否正常
  • 优化:改进用户体验和代码质量

第三方库的使用

天气查询常用 requests库获取网络数据:

bash

pip install requests

错误处理的重要性

程序可能遇到网络错误、数据错误或用户输入错误。使用 try-except捕获异常,提供友好提示。

用户体验设计

好的体验包括:清晰的输入提示、美观的结果展示、贴心的操作引导。

代码示例(5个贴近生活的场景)

示例1:基础天气查询(模拟数据)

python

def get_weather(city):
    weather_data = {
        "北京": {"temperature": 15, "condition": "晴"},
        "上海": {"temperature": 18, "condition": "多云"},
        "广州": {"temperature": 25, "condition": "小雨"}
    }
    if city in weather_data:
        data = weather_data[city]
        return f"{city}天气:{data['condition']},温度{data['temperature']}℃"
    return "抱歉,暂不支持该城市"

if __name__ == "__main__":
    city = input("请输入城市名称:")
    print(get_weather(city))

示例2:添加异常处理

python

import time

def get_weather_with_error_handling(city):
    weather_data = {"北京": {"temperature": 15, "condition": "晴"}}
    try:
        print(f"正在查询{city}的天气...")
        time.sleep(1)  # 模拟网络延迟
        if city in weather_data:
            data = weather_data[city]
            return f"查询成功!{city}:{data['condition']},{data['temperature']}℃"
        return f"查询失败:未找到{city}的天气信息"
    except Exception as e:
        return f"查询异常:请检查网络连接后重试"

print(get_weather_with_error_handling("北京"))

示例3:用户交互优化

python

def get_weather_fancy(city):
    weather_data = {
        "北京": {"temperature": 15, "condition": "晴", "wind": "2级"},
        "上海": {"temperature": 18, "condition": "多云", "wind": "3级"}
    }
    if city not in weather_data:
        return None
    data = weather_data[city]
    emoji = {"晴": "☀️", "多云": "⛅", "小雨": "🌧️"}.get(data["condition"], "🌡️")
    return f"""
    {'=' * 40}
    🌍 城市:{city}
    {emoji} 天气:{data['condition']}
    🌡️ 温度:{data['temperature']}℃
    💨 风力:{data['wind']}
    {'=' * 40}
    """

if __name__ == "__main__":
    print("欢迎使用天气查询系统!支持:北京、上海")
    while True:
        city = input("请输入城市名称(输入q退出):").strip()
        if city.lower() == 'q':
            print("感谢使用,再见!")
            break
        result = get_weather_fancy(city)
        print(result if result else f"抱歉,暂不支持{city}。")

示例4:功能扩展(更多城市、历史查询)

python

from datetime import datetime

class WeatherApp:
    def __init__(self):
        self.weather_data = self.load_weather_data()
        self.history = []
  
    def load_weather_data(self):
        return {
            "北京": {"temp": 15, "condition": "晴", "update_time": "10:00"},
            "上海": {"temp": 18, "condition": "多云", "update_time": "10:05"},
            "广州": {"temp": 25, "condition": "小雨", "update_time": "10:10"}
        }
  
    def query(self, city):
        if city in self.weather_data:
            data = self.weather_data[city]
            self.history.append({"city": city, "time": datetime.now().strftime("%H:%M:%S")})
            return f"{city}:{data['condition']},{data['temp']}℃"
        return f"抱歉,暂不支持{city}"

app = WeatherApp()
print(app.query("北京"))
print(app.query("广州"))

示例5:实用技巧(API密钥管理、缓存)

python

import time
import hashlib

class AdvancedWeatherApp:
    def __init__(self):
        self.cache = {}
        self.cache_duration = 300  # 5分钟
  
    def get_cache_key(self, city):
        return hashlib.md5(city.encode()).hexdigest()
  
    def get_weather(self, city):
        cache_key = self.get_cache_key(city)
        if cache_key in self.cache:
            data, cached_time = self.cache[cache_key]
            if time.time() - cached_time < self.cache_duration:
                print("[缓存命中]")
                return data
  
        # 模拟API调用
        print(f"[API调用] 获取{city}的天气...")
        time.sleep(0.5)
        data = {"temp": 15, "condition": "晴"}
        self.cache[cache_key] = (data, time.time())
        return data

app = AdvancedWeatherApp()
print(app.get_weather("北京"))
print(app.get_weather("北京"))  # 第二次使用缓存

练习题

第1组:基础练习

目标:运行并理解现有脚本

  1. 运行基础脚本
    • 将示例1代码保存为weather.py并运行
    • 查询不同城市,观察输出
    • 思考:输入不支持的城市会怎样?
  2. 理解代码结构
    • 找出函数定义和调用
    • 理解 if __name__ == "__main__":的作用

第2组:应用练习

目标:为脚本添加新功能

  1. 扩展城市数据
    • 在示例1的字典中添加你的城市
    • 保持数据结构一致
  2. 添加天气建议
    • 根据温度提供穿衣建议:
      • 低于10℃:羽绒服
      • 10-20℃:外套
      • 20-30℃:长袖/短袖
      • 高于30℃:短袖,防暑

第3组:综合练习

目标:扩展温度单位转换

  1. 摄氏度转华氏度
    • 华氏度 = 摄氏度 × 1.8 + 32
    • 让用户选择温度单位(C或F)
  2. 完整天气查询系统
    • 综合前5个示例功能
    • 支持多城市查询、友好界面、异常处理、单位转换、历史记录
    • 进阶:尝试真实天气API

总结

恭喜完成第一个Python项目!你实践了:

项目全流程:需求分析→设计→编码→测试→优化关键技术:第三方库使用、错误处理、用户体验设计能力提升:综合运用知识、调试解决问题、代码组织设计

这个项目只是开始,可以继续扩展图形界面、更多天气信息、手机App等。明天我们将进行系列总结!


学习建议

  1. 从简单开始,逐步添加功能
  2. 多写注释便于维护
  3. 遇到问题分解为小步骤
  4. 参考优秀开源项目学习
  5. 保持好奇心不断尝试
18.处理CSV文件 2026-01-21
20.学习总结与进阶方向 2026-01-21

评论区