Python 开发常用语法

34 阅读2分钟

1. 变量

name = "张三"
age = 18
price = 99.9
is_active = True

Python 不需要写类型:

let name = "张三"   # JS
name = "张三"       # Python

2. 基础数据类型

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

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

True
False
None

不是:

true
false
null

3. 字符串

name = "Claude"

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

推荐使用 f-string:

age = 18
print(f"我今年 {age} 岁")

4. 列表 list,类似 JS 数组

names = ["张三", "李四", "王五"]

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

names.append("赵六")

遍历:

for name in names:
    print(name)

5. 字典 dict,类似 JS 对象

user = {
    "name": "张三",
    "age": 18
}

print(user["name"])

修改:

user["age"] = 20
user["city"] = "上海"

遍历:

for key, value in user.items():
    print(key, value)

6. 条件判断

age = 18

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

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

JS:

if (age >= 18) {
  console.log("成年人")
}

Python:

if age >= 18:
    print("成年人")

7. 循环

for 循环

for i in range(5):
    print(i)

输出:

0
1
2
3
4

while 循环

count = 0

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

跳出循环

for i in range(10):
    if i == 5:
        break
    print(i)

跳过本次循环

for i in range(10):
    if i == 5:
        continue
    print(i)

8. 函数

def add(a, b):
    return a + b

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

带默认值:

def say_hello(name="朋友"):
    print(f"你好,{name}")

调用:

say_hello()
say_hello("张三")

9. 类

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()

说明:

__init__

类似构造函数。

self

类似 JS 里的 this

10. 模块导入

导入系统模块:

import os
import sys
import subprocess

导入某个函数:

from pathlib import Path

使用:

import os

print(os.getcwd())

11. 文件读写

读取文件:

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

print(content)

写入文件:

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

追加内容:

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

12. 异常处理

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

常见写法:

try:
    do_something()
except Exception as e:
    print(f"执行失败:{e}")

13. 类型注解

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

def add(a: int, b: int) -> int:
    return a + b

变量也可以写:

name: str = "张三"
age: int = 18

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

14. 常用内置方法

判断类型

isinstance(name, str)
isinstance(age, int)
isinstance(data, list)

判断对象有没有某个属性

hasattr(block, "text")

你前面看到的代码:

if hasattr(block, "text"):
    print(block.text)

意思就是:

如果 block 有 text 属性,就打印 block.text

15. 列表推导式

普通写法:

nums = [1, 2, 3, 4]
result = []

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

简洁写法:

nums = [1, 2, 3, 4]
result = [n * 2 for n in nums]

带条件:

even_nums = [n for n in nums if n % 2 == 0]

16. 常用项目入口写法

很多 Python 文件最后会写:

if __name__ == "__main__":
    main()

完整例子:

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

写入:

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 的雏形:

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

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