Python 语法速成指南:前端开发者视角(JS 类比版)

学习 Agent 开发一段时间了,发现 Python 语法其实和 JavaScript 很像。

这篇文章帮你快速理解项目中用到的所有 Python 语法,用 JavaScript 类比,一看就懂

应该先发出来这个的。。。。现在才补


一、基础语法对比

1.1 变量定义

Python JavaScript
name = "cat" let name = "cat"
count = 10 let count = 10
不需要声明类型 需要 let/const/var

Python 不需要声明变量类型,直接赋值就行

python 复制代码
# Python
name = "cat"
count = 10
is_correct = True  # 注意:True 不是 true
javascript 复制代码
// JavaScript
let name = "cat";
let count = 10;
let isCorrect = true;

1.2 字符串

Python JavaScript
f-string 格式化 模板字符串
"Hello {name}" 不支持
f"Hello {name}" Hello ${name}
python 复制代码
# Python f-string(项目里大量使用)
word = "cat"
cn = "猫"
prompt = f"请讲解单词 '{word}'(意思是'{cn}')"
# 结果:请讲解单词 'cat'(意思是'猫')
javascript 复制代码
// JavaScript 模板字符串
let word = "cat";
let cn = "猫";
let prompt = `请讲解单词 '${word}'(意思是'${cn}')`;

1.3 列表(数组)

Python JavaScript
list Array
[1, 2, 3] [1, 2, 3]
words.append("dog") words.push("dog")
words[0] words[0]
len(words) words.length
python 复制代码
# Python
words = ["cat", "dog", "bird"]
words.append("fish")      # 添加元素
first = words[0]          # 取第一个
count = len(words)        # 获取长度
last = words[-1]          # 取最后一个(JS没有这个!)
javascript 复制代码
// JavaScript
let words = ["cat", "dog", "bird"];
words.push("fish");       // 添加元素
let first = words[0];     // 取第一个
let count = words.length; // 获取长度
let last = words[words.length - 1]; // 取最后一个

1.4 字典(对象)

Python JavaScript
dict Object
{"key": "value"} {"key": "value"}
data["key"] data.keydata["key"]
data.get("key") data.key
python 复制代码
# Python
word = {"en": "cat", "cn": "猫"}
en = word["en"]           # 取值
cn = word.get("cn")       # 取值(不存在返回 None)
word["phonetic"] = "kat"  # 添加属性
javascript 复制代码
// JavaScript
let word = {en: "cat", cn: "猫"};
let en = word.en;          // 取值
let cn = word["cn"];       // 取值(不存在返回 undefined)
word.phonetic = "kat";     // 添加属性

1.5 None vs null

Python JavaScript
None null / undefined
if value is None: if (value === null)
python 复制代码
# Python
result = None
if result is None:
    print("没有结果")
javascript 复制代码
// JavaScript
let result = null;
if (result === null) {
    console.log("没有结果");
}

二、函数对比

2.1 定义函数

Python JavaScript
def func(): function func()
无需 return 类型 无需 return 类型
python 复制代码
# Python
def learn_word(word):
    """学习一个单词"""  # 这是文档字符串
    return f"学习 {word}"

# 调用
result = learn_word("cat")
javascript 复制代码
// JavaScript
function learnWord(word) {
    return `学习 ${word}`;
}

// 调用
let result = learnWord("cat");

2.2 参数解包(项目中大量使用)

python 复制代码
# Python 字典解包(**arguments)
arguments = {"word": "cat", "cn": "猫"}

# 这两种写法等价:
learn_word(**arguments)    # 解包后变成 learn_word(word="cat", cn="猫")
learn_word(word="cat", cn="猫")  # 直接传参数
javascript 复制代码
// JavaScript 对象解包(...arguments)
let arguments = {word: "cat", cn: "猫"};

// 这两种写法等价:
learnWord(...Object.values(arguments)); // JS 不能直接这样用
learnWord(arguments.word, arguments.cn); // 手动传参数

Python 的 **dict 可以直接把字典变成函数参数,JS 没有这个特性


2.3 Lambda(匿名函数)

Python JavaScript
lambda x: x * 2 x => x * 2
python 复制代码
# Python lambda(简单匿名函数)
double = lambda x: x * 2
result = double(5)  # 10
javascript 复制代码
// JavaScript 箭头函数
let double = x => x * 2;
let result = double(5); // 10

三、流程控制对比

3.1 条件判断

Python JavaScript
if/elif/else if/else if/else
and / or / not && / ! / `
python 复制代码
# Python
score = 85
if score >= 90:
    print("优秀")
elif score >= 60:
    print("及格")
else:
    print("不及格")

# 逻辑运算
if score >= 60 and score < 90:
    print("中等")
javascript 复制代码
// JavaScript
let score = 85;
if (score >= 90) {
    console.log("优秀");
} else if (score >= 60) {
    console.log("及格");
} else {
    console.log("不及格");
}

// 逻辑运算
if (score >= 60 && score < 90) {
    console.log("中等");
}

3.2 循环

Python JavaScript
for item in list: for (let item of list)
for i in range(10): for (let i = 0; i < 10; i++)
while condition: while (condition)
python 复制代码
# Python for 循环
words = ["cat", "dog", "bird"]
for word in words:
    print(word)

# Python range 循环
for i in range(3):
    print(i)  # 0, 1, 2

# Python while 循环
count = 0
while count < 3:
    print(count)
    count += 1
javascript 复制代码
// JavaScript for...of 循环
let words = ["cat", "dog", "bird"];
for (let word of words) {
    console.log(word);
}

// JavaScript for 循环
for (let i = 0; i < 3; i++) {
    console.log(i);
}

// JavaScript while 循环
let count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

3.3 列表推导式(Python 特色)

感觉一行代码说了一段话~~

python 复制代码
# Python 列表推导式(一行代码创建新列表)
words = ["cat", "dog", "bird"]
upper_words = [w.upper() for w in words]  # ["CAT", "DOG", "BIRD"]

# 带条件过滤
long_words = [w for w in words if len(w) > 3]  # ["bird"]

# 项目中用到的例子:从错题本移除单词
user_memory["wrong_words"] = [
    w for w in user_memory["wrong_words"] if w["en"] != en
]
javascript 复制代码
// JavaScript 用 map/filter 实现
let words = ["cat", "dog", "bird"];
let upperWords = words.map(w => w.toUpperCase()); // ["CAT", "DOG", "BIRD"]

// 带条件过滤
let longWords = words.filter(w => w.length > 3); // ["bird"]

// 从错题本移除单词
userMemory.wrongWords = userMemory.wrongWords.filter(w => w.en !== en);

四、模块导入对比

Python JavaScript
import module import module
from module import func import { func } from module
import module as m import * as m from module
python 复制代码
# Python 导入
import requests                           # 导入整个模块
from flask import Flask, request          # 导入部分
import json
from datetime import datetime
javascript 复制代码
// JavaScript 导入
import requests from 'requests';          // 导入整个模块
import { Flask, request } from 'flask';   // 导入部分(ES6)
import * as json from 'json';

五、异步/并发对比

这是最大的区别!Python 默认同步,JS 默认异步,这个思路一点要转变

5.1 HTTP 请求

python 复制代码
# Python requests(同步,会阻塞)
import requests

response = requests.post(url, headers=headers, json=data)
# 等待响应完成,然后继续
result = response.json()
javascript 复制代码
// JavaScript fetch(异步,Promise)
const response = await fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
});
const result = await response.json();

// 或者用 Promise
fetch(url, options).then(res => res.json()).then(data => {
    console.log(data);
});

5.2 流式响应(项目中大量使用)

python 复制代码
# Python 流式处理
response = requests.post(url, stream=True)  # stream=True 开启流式

for line in response.iter_lines():
    if line:
        chunk = json.loads(line)
        content = chunk["choices"][0]["delta"]["content"]
        print(content)
javascript 复制代码
// JavaScript 流式处理(Fetch API)
const response = await fetch(url, options);
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const data = JSON.parse(chunk);
    console.log(data);
}

六、常用库对比

6.1 HTTP 请求库

Python JavaScript
requests fetch / axios
requests.post() fetch()axios.post()
python 复制代码
# Python requests
import requests

response = requests.post(
    "https://api.example.com/chat",
    headers={"Authorization": "Bearer xxx"},
    json={"model": "glm-5", "messages": [...]}
)

if response.status_code == 200:
    result = response.json()
javascript 复制代码
// JavaScript fetch
const response = await fetch("https://api.example.com/chat", {
    method: "POST",
    headers: { Authorization: "Bearer xxx" },
    body: JSON.stringify({ model: "glm-5", messages: [...] })
});

if (response.ok) {
    const result = await response.json();
}

// JavaScript axios
const result = await axios.post("https://api.example.com/chat", {
    model: "glm-5",
    messages: [...]
}, {
    headers: { Authorization: "Bearer xxx" }
});

6.2 JSON 处理

Python JavaScript
json.loads() JSON.parse()
json.dumps() JSON.stringify()
python 复制代码
# Python JSON
import json

# 解析 JSON 字符串
data = json.loads('{"name": "cat"}')  # 变成字典

# 转成 JSON 字符串
json_str = json.dumps(data, ensure_ascii=False)  # 中文不转义
javascript 复制代码
// JavaScript JSON
// 解析 JSON 字符串
let data = JSON.parse('{"name": "cat"}');  // 变成对象

// 转成 JSON 字符串
let jsonStr = JSON.stringify(data);

6.3 文件操作

Python JavaScript
open() fs.readFileSync()
with open() Node.js 没有
python 复制代码
# Python 文件操作(项目中用来保存用户数据)
import json

# 读取文件
with open("user_memory.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# 写入文件
with open("user_memory.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# with 语句会自动关闭文件,不需要手动 close()
javascript 复制代码
// Node.js 文件操作
const fs = require('fs');

// 读取文件
const data = JSON.parse(fs.readFileSync('user_memory.json', 'utf8'));

// 写入文件
fs.writeFileSync('user_memory.json', JSON.stringify(data, null, 2));

七、Flask vs Express

7.1 创建应用

python 复制代码
# Python Flask
from flask import Flask, request, Response, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/chat", methods=["POST"])
def chat():
    user_input = request.json.get("message", "")
    return {"reply": "Hello"}

if __name__ == "__main__":
    app.run(debug=True, port=5000)
javascript 复制代码
// JavaScript Express
import express from 'express';

const app = express();
app.use(express.json());

app.get("/", (req, res) => {
    res.sendFile("index.html");
});

app.post("/chat", (req, res) => {
    const userInput = req.body.message || "";
    res.json({ reply: "Hello" });
});

app.listen(5000, () => {
    console.log("Server running on port 5000");
});

7.2 路由装饰器

python 复制代码
# Python Flask 装饰器(@app.route)
@app.route("/points", methods=["GET"])
def get_points():
    return {"points": 100}

@app.route("/points/add", methods=["POST"])
def add_points():
    action = request.json.get("action")
    return {"added": 10}
javascript 复制代码
// JavaScript Express 路由
app.get("/points", (req, res) => {
    res.json({ points: 100 });
});

app.post("/points/add", (req, res) => {
    const action = req.body.action;
    res.json({ added: 10 });
});

7.3 流式响应

python 复制代码
# Python Flask 流式响应(SSE)
def generate():
    for i in range(5):
        yield f"data: {i}\n\n"
    yield "data: [DONE]\n\n"

return Response(generate(), mimetype="text/event-stream")
javascript 复制代码
// JavaScript Express 流式响应
res.setHeader('Content-Type', 'text/event-stream');

for (let i = 0; i < 5; i++) {
    res.write(`data: ${i}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();

八、异常处理

python 复制代码
# Python try/except
try:
    response = requests.post(url, json=data, timeout=30)
    result = response.json()
except requests.exceptions.RequestException as e:
    print(f"网络错误: {e}")
except json.JSONDecodeError as e:
    print(f"JSON解析错误: {e}")
javascript 复制代码
// JavaScript try/catch
try {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(data)
    });
    const result = await response.json();
} catch (e) {
    console.log(`错误: ${e}`);
}

九、项目中实际用到的代码解析

9.1 字典解包 **arguments

python 复制代码
# Function Calling 中用到的
tool_call["function"]["arguments"] = '{"word": "cat"}'
arguments = json.loads(tool_call["function"]["arguments"])
# 得到:{"word": "cat"}

# 用 **arguments 解包,自动匹配函数参数
result = learn_word(**arguments)
# 相当于:learn_word(word="cat")

9.2 列表推导式

python 复制代码
# 从错题本移除单词(项目中用到)
user_memory["wrong_words"] = [
    w for w in user_memory["wrong_words"] if w["en"] != en
]
# 等价于:
new_list = []
for w in user_memory["wrong_words"]:
    if w["en"] != en:
        new_list.append(w)
user_memory["wrong_words"] = new_list

9.3 yield 生成器

python 复制代码
# Flask 流式响应中用到
def generate():
    full_reply = ""
    for line in response.iter_lines():
        if line:
            content = parse_content(line)
            full_reply += content
            yield f"data: {content}\n\n"  # 每次yield一块数据
    
    yield "data: [DONE]\n\n"

# yield 是"暂停并返回",下次调用继续从这里开始

9.4 global 关键字

python 复制代码
# 项目中修改全局变量
messages = []

def clear():
    global messages  # 声明使用全局变量
    messages.clear()  # 否则会创建新的局部变量

9.5 编码处理

python 复制代码
# 文件开头声明编码
# -*- coding: utf-8 -*-

# 命令行输出中文
import sys
sys.stdout.reconfigure(encoding='utf-8')

# 读取/写入文件时指定编码
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

十、速查表

Python JavaScript 说明
True/False true/false 布尔值
None null/undefined 空值
and/or/not `&&/
len(x) x.length 长度
list.append() array.push() 添加元素
dict["key"] obj.key 取值
f"{var}" ${var} 字符串格式化
for x in list: for (let x of list) 循环
if/elif/else if/else if/else 条件
def func(): function func() 函数定义
lambda x: x*2 x => x*2 匿名函数
json.loads() JSON.parse() 解析JSON
json.dumps() JSON.stringify() 转JSON
try/except try/catch 异常处理
import x import x 导入
with open() 文件操作
**dict 字典解包
[x for x in list] list.map() 列表推导
yield 生成器

写给前端开发者的 Python 速成指南,用 JS 类比,一看就懂

相关推荐
JYeontu2 小时前
轮播图不够惊艳?试下这个立体卡片轮播图
前端·javascript·css
张就是我1065922 小时前
从前端角度理解 CVE-2026-31431
前端
AGoodrMe2 小时前
swift基础之async/await
前端·ios
Binary_Soul2 小时前
一文读懂:如何让 Claude Code 拥有"过目不忘"的记忆力
人工智能
irving同学462382 小时前
从零搭建生产级 RAG:Embedding、Chunking、Hybrid Search 与 Reranker
前端·后端
黎阳之光2 小时前
黎阳之光:以视频孪生重构智慧医院信息化,打造高标项目核心竞争力
大数据·人工智能·物联网·算法·数字孪生
卡卡军2 小时前
vue3-sketch-ruler v3 升级详解:从 Vue 组件到跨框架标尺引擎
前端
还有多久拿退休金2 小时前
让看不见的 AI 动手画画——我意外造出了一个"绘图 Agent"
前端
东风破_2 小时前
Claude Code 实战指南:像带实习生一样让 AI 帮你维护项目
人工智能