前端转AI系列(一):Python 基础速通

0 阅读4分钟

系列导读:本系列面向有 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}

前端对比速查

PythonJavaScript说明
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 私有字段)

前端对比速查

PythonJavaScript说明
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


快速映射表

概念PythonJavaScript
代码块缩进{ }
变量声明x = 1let x = 1
常量UPPER_CASE = 1(约定)const X = 1
字符串格式化f"{name}"`${name}`
布尔值True / Falsetrue / false
空值Nonenull / undefined
逻辑运算and / or / not&& / || / !
自增i += 1i++
相等比较==(无隐式转换)===(推荐)
数组方法append / pop / insertpush / pop / splice
遍历for item in listfor...of
导出无 export(文件即模块)export
包管理pipnpm / yarn / pnpm
虚拟环境venvnode_modules(隔离方式不同)

下一篇预告:在掌握了 Python 基础语法后,我们将在 前端转AI系列(二):Python 进阶 中学习装饰器、生成器、异步编程(async/await)与类型系统,这些是阅读 AI 框架源码的必备知识。敬请期待!