Python 开发常用语法

1. 变量

ini 复制代码
name = "张三"
age = 18
price = 99.9
is_active = True

Python 不需要写类型:

ini 复制代码
let name = "张三"   # JS
name = "张三"       # Python

2. 基础数据类型

ini 复制代码
name = "Claude"        # 字符串 str
age = 18               # 整数 int
price = 12.5           # 小数 float
is_ok = True           # 布尔 bool
empty = None           # 空值 None

注意 Python 的布尔值首字母大写:

python 复制代码
True
False
None

不是:

csharp 复制代码
true
false
null

3. 字符串

python 复制代码
name = "Claude"

print("hello " + name)
print(f"hello {name}")

推荐使用 f-string:

python 复制代码
age = 18
print(f"我今年 {age} 岁")

4. 列表 list,类似 JS 数组

ini 复制代码
names = ["张三", "李四", "王五"]

print(names[0])      # 张三
print(names[-1])     # 王五

names.append("赵六")

遍历:

bash 复制代码
for name in names:
    print(name)

5. 字典 dict,类似 JS 对象

sql 复制代码
user = {
    "name": "张三",
    "age": 18
}

print(user["name"])

修改:

sql 复制代码
user["age"] = 20
user["city"] = "上海"

遍历:

scss 复制代码
for key, value in user.items():
    print(key, value)

6. 条件判断

bash 复制代码
age = 18

if age >= 18:
    print("成年人")
elif age >= 12:
    print("青少年")
else:
    print("儿童")

Python 靠缩进表示代码块,不用 {}

JS:

erlang 复制代码
if (age >= 18) {
  console.log("成年人")
}

Python:

bash 复制代码
if age >= 18:
    print("成年人")

7. 循环

for 循环

scss 复制代码
for i in range(5):
    print(i)

输出:

复制代码
0
1
2
3
4

while 循环

bash 复制代码
count = 0

while count < 5:
    print(count)
    count += 1

跳出循环

arduino 复制代码
for i in range(10):
    if i == 5:
        break
    print(i)

跳过本次循环

arduino 复制代码
for i in range(10):
    if i == 5:
        continue
    print(i)

8. 函数

sql 复制代码
def add(a, b):
    return a + b

result = add(1, 2)
print(result)

带默认值:

python 复制代码
def say_hello(name="朋友"):
    print(f"你好,{name}")

调用:

scss 复制代码
say_hello()
say_hello("张三")

9. 类

ruby 复制代码
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"你好,我是 {self.name}")

user = User("张三", 18)
user.say_hello()

说明:

markdown 复制代码
__init__

类似构造函数。

lua 复制代码
self

类似 JS 里的 this

10. 模块导入

导入系统模块:

arduino 复制代码
import os
import sys
import subprocess

导入某个函数:

javascript 复制代码
from pathlib import Path

使用:

lua 复制代码
import os

print(os.getcwd())

11. 文件读写

读取文件:

python 复制代码
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()

print(content)

写入文件:

python 复制代码
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("hello")

追加内容:

python 复制代码
with open("test.txt", "a", encoding="utf-8") as f:
    f.write("\nnew line")

12. 异常处理

python 复制代码
try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以 0")
except Exception as e:
    print("发生错误:", e)
finally:
    print("执行结束")

常见写法:

python 复制代码
try:
    do_something()
except Exception as e:
    print(f"执行失败:{e}")

13. 类型注解

Python 可以不写类型,但现在开发中常写类型注解:

php 复制代码
def add(a: int, b: int) -> int:
    return a + b

变量也可以写:

ini 复制代码
name: str = "张三"
age: int = 18

这只是提示,不像 TypeScript 那样强制运行时校验。

14. 常用内置方法

判断类型

scss 复制代码
isinstance(name, str)
isinstance(age, int)
isinstance(data, list)

判断对象有没有某个属性

python 复制代码
hasattr(block, "text")

你前面看到的代码:

python 复制代码
if hasattr(block, "text"):
    print(block.text)

意思就是:

scss 复制代码
如果 block 有 text 属性,就打印 block.text

15. 列表推导式

普通写法:

ini 复制代码
nums = [1, 2, 3, 4]
result = []

for n in nums:
    result.append(n * 2)

简洁写法:

ini 复制代码
nums = [1, 2, 3, 4]
result = [n * 2 for n in nums]

带条件:

ini 复制代码
even_nums = [n for n in nums if n % 2 == 0]

16. 常用项目入口写法

很多 Python 文件最后会写:

ini 复制代码
if __name__ == "__main__":
    main()

完整例子:

css 复制代码
def main():
    print("程序开始运行")

if __name__ == "__main__":
    main()

意思是:

只有直接运行这个文件时,才执行 main()

例如:

复制代码
python3 app.py

会执行。

但如果这个文件被别人 import,就不会自动执行 main()

二、看 Agent 代码时,重点掌握这些语法

你现在看 s01_agent_loop.py,重点要懂这些:

语法

用途

import

引入库

def

定义函数

while True

无限循环

if / elif / else

条件判断

for block in response.content

遍历模型返回内容

list

存消息历史

dict

表示 message / tool

subprocess.run()

执行 shell 命令

try / except

捕获异常

hasattr()

判断对象是否有属性

isinstance()

判断数据类型

return

返回结果 / 结束函数

三、最小 Python 练习文件

你可以新建一个:

复制代码
demo.py

写入:

python 复制代码
def run_bash(command: str) -> str:
    print(f"准备执行命令:{command}")
    return "执行完成"

def main():
    history = []

    while True:
        query = input("请输入问题:")

        if query == "exit":
            break

        history.append({
            "role": "user",
            "content": query
        })

        result = run_bash(query)

        history.append({
            "role": "assistant",
            "content": result
        })

        print("当前历史记录:")
        print(history)

if __name__ == "__main__":
    main()

运行:

复制代码
python3 demo.py

这个小例子已经有 Agent Loop 的雏形:

rust 复制代码
用户输入 -> 记录历史 -> 执行动作 -> 记录结果 -> 继续循环

先掌握这些,再看 s01_agent_loop.py 会顺很多。

相关推荐
撑伞的鱼99371 天前
C++开发用什么AI编程工具效果好?2026年实测横评(附选型指南)
开发语言·c++·ai编程·cursor
旋生万物8 天前
五条几何公理重构元素周期表:从量子力学到螺旋拓扑的降维(AI 编程时代的微观启示)
重构·ai编程·代码审计·cursor·ai agent·mcp协议·claudecode
武雄(小星Ai)9 天前
2026 AI编程工具横评:Trae、Cursor、Copilot、Claude Code实测对比
ai·copilot·cursor·编程工具·trae·claude code·对比评测
咖啡星人k9 天前
AI 编程工具集体变脸:Cursor 漏洞、TRAE 限额、Claude Code 数据收集风波
人工智能·安全·microsoft·cursor·trae·ai编程工具
csdn_aspnet13 天前
如何将 Cursor MCP 与 VS Code 连接
vscode·cursor·mcp·composio
思码梁田13 天前
CSS cursor 属性全解析:从“小手“开始,玩转鼠标光标
前端·css·计算机外设·cursor·pointer
武雄(小星Ai)15 天前
2026年7月 AI 编程工具横评:Claude Code vs Cursor vs GitHub Copilot 实测对比
ai·开发工具·claude·cursor·对比评测
redreamSo15 天前
32 个 AI 编程工具的配置都放哪,这个仓库整理清楚了
ai编程·claude·cursor
唠点键盘之外的17 天前
10 Spring Boot + 大模型:Java 项目接入 AI 的三种姿势
java·spring boot·aigc·cursor
仙逆GPT19 天前
Cursor Agent一直卡住?自动执行和权限确认怎么排查
ai编程·cursor·ai agent·代码审查·cursor agent