系列导读:本系列面向有 JavaScript/前端开发经验的工程师,通过对比映射的方式快速掌握 Python,为进入 AI 领域铺路。
📖 系列篇章:
- (一)Python 基础速通 ← 你在这里
- (二)Python 进阶 — 装饰器、生成器、异步与类型系统
- (三)AI 框架篇 — LangChain / LlamaIndex 实战入门
- (四)AI 应用实战篇 — RAG、Agent 与工具调用
1. 变量与数据类型
Python 是动态类型语言,和 JS 一样无需声明类型。
# 基本类型
name = "Alice" # 字符串 ↔ JS: string
age = 25 # 整数 ↔ JS: number(JS 不区分整数和浮点数)
height = 1.68 # 浮点数 ↔ JS: number
is_student = True # 布尔值 ↔ JS: true(注意大写 T)
# 查看类型
print(type(age)) # <class 'int'> ↔ JS: typeof age → "number"
# 多重赋值(JS 不支持这种写法)
x, y, z = 1, 2, 3
前端对比:Python 的
True/False/None对应 JS 的true/false/null,首字母大写。Python 没有类似 JS 的undefined,只有None。
常用类型转换:int(), float(), str(), bool()
2. 运算符
# 算术运算符
a, b = 10, 3
print(a + b) # 13 加
print(a - b) # 7 减
print(a * b) # 30 乘
print(a / b) # 3.333... 除(始终返回浮点数)
print(a // b) # 3 整除(JS 没有对应运算符,需用 Math.floor(a/b))
print(a % b) # 1 取余
print(a ** b) # 1000 幂 ↔ JS: Math.pow(a, b) 或 a ** b
# 比较运算符
print(a == b) # False 值相等 ↔ JS: ===(Python 没有隐式类型转换的问题)
print(a != b) # True
# 逻辑运算符 — 注意用英文单词,不是符号
print(True and False) # False ↔ JS: &&
print(True or False) # True ↔ JS: ||
print(not True) # False ↔ JS: !
3. 条件语句与循环
核心区别:Python 用缩进代替花括号,条件后加冒号 :。
# if-elif-else ↔ JS: if / else if / else
score = 85
if score >= 90: # 注意冒号
grade = "A" # 缩进代替 { }
elif score >= 80: # elif ↔ JS: else if
grade = "B"
else:
grade = "C"
# for 循环
for i in range(5): # range(5) → 0,1,2,3,4 ↔ JS: for(let i=0; i<5; i++)
print(i)
# 遍历列表 ↔ JS: for...of
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# while 循环 ↔ JS 完全一致
count = 0
while count < 3:
print(count)
count += 1 # Python 没有 count++
# 循环控制:continue / break 与 JS 一致
for i in range(10):
if i == 3:
continue
if i == 7:
break
print(i)
前端对比:Python 的
for...in遍历的是 key(类似 JS 的for...in),for...of不存在,但直接for item in list等价于 JS 的for...of。
4. 函数
# 基本定义 ↔ JS: function greet(name) { return ... }
def greet(name):
return f"Hello, {name}!"
# 默认参数 ↔ JS: function power(base, exponent = 2)
def power(base, exponent=2):
return base ** exponent
# 可变参数 ↔ JS: function sumAll(...args)
def sum_all(*args):
return sum(args)
# 关键字参数(JS 没有对应特性,类似解构传参)
def configure(width, height, color):
pass
configure(width=800, height=600, color="red") # 按参数名传值
# 匿名函数 ↔ JS: const square = x => x ** 2
square = lambda x: x ** 2
print(square(5)) # 25
前端对比:Python 的关键字参数
configure(color="red")是 JS 没有的特性,调用时可以按名称传参,非常实用。
5. 列表、元组、字典、集合
# 列表 list ↔ JS: Array
nums = [1, 2, 3, 4, 5]
nums.append(6) # ↔ JS: nums.push(6)
nums.insert(0, 0) # ↔ JS: nums.unshift(0)(但 insert 可指定位置)
nums.pop() # ↔ JS: nums.pop()
print(nums[1:3]) # 切片 [2, 3] ↔ JS: nums.slice(1, 3)
# 元组 tuple(不可变列表,JS 没有对应类型,类似 Object.freeze(arr))
point = (10, 20)
x, y = point # 解包 ↔ JS: const [x, y] = point
# 字典 dict ↔ JS: Object / Map
person = {"name": "Alice", "age": 25}
person["city"] = "Beijing" # ↔ JS: person.city = "Beijing"
print(person.get("name")) # ↔ JS: person.name 或 person?.name
print(person.keys()) # ↔ JS: Object.keys(person)
print(person.values()) # ↔ JS: Object.values(person)
# 集合 set ↔ JS: Set
s = {1, 2, 3, 2, 1} # 自动去重 → {1, 2, 3}
s.add(4) # ↔ JS: set.add(4)
s.discard(5) # 移除,不存在不报错
print({1, 2} & {2, 3}) # 交集 {2} ↔ JS: 无原生支持
print({1, 2} | {2, 3}) # 并集 {1, 2, 3}
前端对比速查:
Python JavaScript 说明 listArray可变有序序列 tupleObject.freeze(arr)不可变有序序列 dictObject/Map键值对 setSet唯一值集合
6. 字符串操作
s = "Hello, World!"
# 常用方法(大部分与 JS 一致)
print(s.upper()) # HELLO, WORLD! ↔ JS: s.toUpperCase()
print(s.lower()) # hello, world! ↔ JS: s.toLowerCase()
print(s.split(",")) # ['Hello', ' World!'] ↔ JS: s.split(",")
print(s.replace("World", "Python")) # ↔ JS: s.replace("World", "Python")
print(s.strip()) # 去除首尾空白 ↔ JS: s.trim()
print(s.startswith("Hello")) # ↔ JS: s.startsWith("Hello")
print(s.find("World")) # 7,返回索引 ↔ JS: s.indexOf("World")
# f-string 格式化 ↔ JS: 模板字符串 `My name is ${name}`
name = "Alice"
age = 25
print(f"My name is {name}, I'm {age} years old.")
# ↑ 完全等价于 JS: `My name is ${name}, I'm ${age} years old.`
# 切片(JS 用 slice/substring)
print(s[0:5]) # Hello ↔ JS: s.slice(0, 5)
print(s[-6:-1]) # World ↔ JS: s.slice(-6, -1)
7. 文件读写
# 读取文件 ↔ JS(Node): fs.readFileSync("example.txt", "utf-8")
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
lines = f.readlines() # 按行读取为列表
line = f.readline() # 读取一行
# 写入文件 ↔ JS(Node): fs.writeFileSync("output.txt", "Hello\n")
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
f.writelines(["line1\n", "line2\n"])
# 追加模式 "a" = append
with open("log.txt", "a", encoding="utf-8") as f:
f.write("new log entry\n")
前端对比:Python 的
with open(...) as f自动关闭文件,类似 JS 中手动调try...finally关闭资源。Node.js 中更常用fs.readFileSync/fs.writeFileSync一步到位。
8. 异常处理
# 基本结构 ↔ JS: try / catch / finally
try: # ↔ JS: try {
result = 10 / 0
except ZeroDivisionError as e: # ↔ JS: catch(e) {
print(f"错误: {e}")
except Exception as e: # 可以有多个 except(JS 只有一个 catch)
print(f"其他错误: {e}")
else: # JS 没有对应语法
print("执行成功")
finally: # ↔ JS: finally {
print("无论是否出错都会执行")
# 抛出异常 ↔ JS: throw new Error("除数不能为零")
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
前端对比:Python 支持
else子句(无异常时执行)和多个except分支,比 JS 的try...catch更精细。
速记
- 列表(List) —— 有序、可变
- 元组(Tuple) —— 有序、不可变
- 字典(Dict) —— 键值对、可变
- 集合(Set) —— 无序、唯一
9. 类与对象
# 定义类 ↔ JS: class Person { constructor(name, age) { ... } }
class Person:
def __init__(self, name, age): # ↔ JS: constructor(name, age)
self.name = name # self ↔ JS: this
self.age = age
def say_hello(self): # 注意 self 参数,JS 方法不需要写 this
return f"Hello, I'm {self.name}"
def __str__(self): # ↔ JS: toString()
return f"Person({self.name}, {self.age})"
# 创建实例(不需要 new 关键字)
p = Person("Alice", 25) # ↔ JS: new Person("Alice", 25)
print(p.say_hello())
# 继承 ↔ JS: class Student extends Person
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age) # ↔ JS: super(name, age)
self.grade = grade
def study(self):
return f"{self.name} is studying"
# 私有属性(双下划线前缀)
class User:
def __init__(self, password):
self.__password = password # ↔ JS: #password(ES2022 私有字段)
前端对比速查:
Python JavaScript 说明 selfthis实例引用(Python 需显式声明为方法第一个参数) __init__constructor构造函数 super()super()调用父类构造函数 __str__toString()字符串表示 __xxx#xxx私有属性
10. 模块与包
# 导入模块 ↔ JS: import math from 'math'(ES Module)
import math # ↔ JS: import * as math from 'math'
from datetime import datetime # ↔ JS: import { datetime } from 'datetime'
from os.path import join as path_join # ↔ JS: import { join as pathJoin } from 'path'
# 使用别名
import numpy as np # ↔ JS: import * as np from 'numpy'
# 模块搜索路径
import sys
print(sys.path)
# 包结构 ↔ JS: npm 包 + package.json
# mypackage/
# __init__.py ← 标识这是一个包(类似 package.json 的角色)
# module1.py
# module2.py
# 在 __init__.py 中导出 ↔ JS: export
# from .module1 import my_function
前端对比:Python 的
import机制与 JS ES Module 类似,但 Python 不需要解构{ }来导入具名导出,而是用from ... import ...语法。
常用标准库:math, random, datetime, json, re, collections, itertools
快速映射表
| 概念 | Python | JavaScript |
|---|---|---|
| 代码块 | 缩进 | { } |
| 变量声明 | x = 1 | let x = 1 |
| 常量 | UPPER_CASE = 1(约定) | const X = 1 |
| 字符串格式化 | f"{name}" | `${name}` |
| 布尔值 | True / False | true / false |
| 空值 | None | null / undefined |
| 逻辑运算 | and / or / not | && / || / ! |
| 自增 | i += 1 | i++ |
| 相等比较 | ==(无隐式转换) | ===(推荐) |
| 数组方法 | append / pop / insert | push / pop / splice |
| 遍历 | for item in list | for...of |
| 导出 | 无 export(文件即模块) | export |
| 包管理 | pip | npm / yarn / pnpm |
| 虚拟环境 | venv | node_modules(隔离方式不同) |
下一篇预告:在掌握了 Python 基础语法后,我们将在 前端转AI系列(二):Python 进阶 中学习装饰器、生成器、异步编程(
async/await)与类型系统,这些是阅读 AI 框架源码的必备知识。敬请期待!