M2.1 · Python 速成
掌握程度:独立实现
学生转行工程师
📘 已发布学习资料
M2.1 Python 速成
目标:零基础也能跑通 Python 基础 + 用 requests 调一个公开 API(为后面调大模型打底)。
1. 变量、数据类型、条件、循环
# 变量与基本类型
name = "瑞冬" # 字符串 str
count = 546 # 整数 int
price = 29.9 # 浮点 float
done = False # 布尔 bool
tags = ["AI", "Agent"] # 列表 list
# 条件
if count > 500:
print("视频很多")
elif count > 100:
print("视频不少")
else:
print("还差点")
# 循环
for t in tags:
print(t)
2. 函数与模块
def add(a, b):
return a + b
# 模块:把常用功能放进文件,用 import 复用
# utils.py 里写:def format_name(n): return f"Hi {n}"
# 这里用:from utils import format_name
3. 文件读写
# 写
with open("note.txt", "w", encoding="utf-8") as f:
f.write("今天学了 Python 基础")
# 读
with open("note.txt", "r", encoding="utf-8") as f:
text = f.read()
print(text)
4. 用 requests 发 HTTP 请求
先安装:pip install requests
import requests
# 调一个公开测试 API:查询某 IP 的地理位置
resp = requests.get("https://ipapi.co/8.8.8.8/json/")
data = resp.json() # 把返回的 JSON 字符串转成 dict
print(data["country_name"], data["city"])
# 带参数
resp = requests.get("https://api.github.com/search/repositories",
params={"q": "agent", "sort": "stars"})
print(resp.json()["total_count"])
5. 实战:写脚本调一个公开 API
任务:写一个脚本,输入一个城市名,输出当地天气(用公开免费接口 wttr.in)。
import requests
def get_weather(city: str):
# wttr.in 支持直接返回 JSON
resp = requests.get(f"https://wttr.in/{city}?format=j1", timeout=10)
if resp.status_code != 200:
return "查询失败"
d = resp.json()
cur = d["current_condition"][0]
return f"{city} 当前 {cur['temp_C']}°C,天气 {cur['lang_zh'][0]['value']}"
print(get_weather("Beijing"))
动手练习
- 本地装好 Python(python.org 下载),跑通上面每一段。
- 改
get_weather让它同时返回"今日最高/最低温"(提示:看返回 JSON 的weather[0])。 - 写一个函数
word_count(text),统计一段文字的词频,输出出现最多的 3 个词。
自测
list和dict分别适合存什么结构的数据?with open(...)比直接open()好在哪(提示:自动关文件)?resp.json()把什么变成了什么?如果返回的不是合法 JSON 会怎样?