Python精选200Tips:151-155


运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12

往期链接:

1-5 6-10 11-20 21-30 31-40 41-50
51-60:函数 61-70:类 71-80:编程范式及设计模式
81-90:Python编码规范 91-100:Python自带常用模块-1
101-105:Python自带模块-2 106-110:Python自带模块-3
111-115:Python常用第三方包-频繁使用 116-120:Python常用第三方包-深度学习
121-125:Python常用第三方包-爬取数据 126-130:Python常用第三方包-为了乐趣
131-135:Python常用第三方包-拓展工具1 136-140:Python常用第三方包-拓展工具2

Python项目实战

141-145 146-150

P151–气象数据爬取

技术栈:数据爬虫
import requests

API_KEY = 'd0d3ed025*******2f14da'  # 请替换为你的 OpenWeatherMap API 密钥
BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'

def get_weather(city):
    # 构建请求 URL
    url = f"{
     BASE_URL}?q={
     city}&appid={
     API_KEY}&units=metric"  # 使用摄氏度
    response = requests.get(url)

    # 检查响应状态
    if response.status_code == 200:
        data = response.json()
        return data
    else:
        print(f"无法获取天气数据: {
     response.status_code}")
        return None

def display_weather(data):
    if data:
        city = data['name']
        temperature = data['main']['temp']
        weather_description = data['weather'][0]['description']
        humidity = data['main']['humidity']
        wind_speed = data['wind']['speed']

        print(f"城市: {
     city}")
        print(f"温度: {
     temperature}°C")
        print(f"天气: {
     weather_description}")
        print(f"湿度: {
     humidity}%")
        print(f"风速: {
     wind_speed} m/s")
    else:
        print("没有可显示的天气数据。")

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

在这里插入图片描述

P152–求解数独问题

技术栈:代码逻辑+回溯法
def is_valid(board, row, col, num):
    # 检查在指定位置放置数字是否有效

    # 检查行
    for x in range(9):
        if board[row][x] == num:
            return False

    # 检查列
    for x in range(9):
        if board[x][col] 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnFany

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值