Python练习3—天气查询小工具

20 阅读2分钟
import random

# 本地存储的天气数据(可以自己修改)
weather_data = {
    "北京": {"temp": 5, "weather": "晴", "humidity": 30},
    "上海": {"temp": 12, "weather": "多云", "humidity": 50},
    "广州": {"temp": 20, "weather": "小雨", "humidity": 70},
    "深圳": {"temp": 22, "weather": "阴", "humidity": 65},
    "香港": {"temp": 25, "weather": "晴", "humidity": 60},
}

#city的部分其实只是一个代称,代指用户输入的部分,根据用户输入的东西到字典里面进行内容的查找

def get_weather(city):
    city = city.title()  # 自动将输入首字母大写
    if city in weather_data:
        data = weather_data[city]

        # 加一点随机变化,让它看起来像预测天气
        temp = data['temp'] + random.randint(-2, 2)
        humidity = data['humidity'] + random.randint(-5, 5)
        weather = data['weather']

        print(f"📍 城市:{city}")
        print(f"🌡️ 温度:{temp}°C")
        print(f"🌥️ 天气:{weather}")
        print(f"💧 湿度:{humidity}%")
    else:
        print("❌ 没有找到这个城市哦~")

# 主程序
city = input("请输入城市名称:")
get_weather(city)
import random

# 本地存储的天气数据(可以自己修改)
weather_data = {
    "北京": {"temp": 5, "weather": "晴", "humidity": 30},
    "上海": {"temp": 12, "weather": "多云", "humidity": 50},
    "广州": {"temp": 20, "weather": "小雨", "humidity": 70},
    "深圳": {"temp": 22, "weather": "阴", "humidity": 65},
    "香港": {"temp": 25, "weather": "晴", "humidity": 60},
}

# 天气对应 emoji
weather_emoji = {
    "晴": "☀️",
    "多云": "🌥️",
    "阴": "☁️",
    "小雨": "🌧️",
    "雷阵雨": "⛈️"
}

# 湿度等级提示函数
def humidity_level(h):
    if h < 40:
        return "干燥 🏜️"
    elif 40 <= h <= 60:
        return "舒适 🌿"
    else:
        return "潮湿 🌧️"

# 查询天气函数
def get_weather(city):
    city = city.strip().title()  # 去掉首尾空格并首字母大写
    if city in weather_data:
        data = weather_data[city]

        # 随机生成今天和未来两天的温度变化,直接利用随机函数在原函数提供的数值上面进行调整
        temps = [data['temp'] + random.randint(-2, 2) for _ in range(3)]
        #temps是一个单独的数组,就是需要把原本字典里面的温度单独拿出来,进行数据上的加减分析,从而组成一个数组
        humidity = data['humidity'] + random.randint(-5, 5)
        weather = data['weather']
        emoji = weather_emoji.get(weather, "")

        print(f"\n📍 城市:{city}")
        print(f"🌥️ 天气:{weather} {emoji}")
        print(f"💧 湿度:{humidity}% ({humidity_level(humidity)})")
        print("🌡️ 未来三天天气预测:")
        days = ["今天", "明天", "后天"]
        for i in range(3):
            print(f"   {days[i]}{temps[i]}°C {weather} {emoji}")
    else:
        print("❌ 没有找到这个城市哦~")
        print("可查询城市列表:", ", ".join(weather_data.keys()))

# 主程序循环
print("欢迎使用离线天气查询小工具!输入“退出”即可结束查询。")
while True:
    city = input("\n请输入城市名称:")
    if city.strip() == "退出":
        print("💖 感谢使用,再见~")
        break
    get_weather(city)