3.1 条件语句
if语句
# 基本if语句
age = 18
if age >= 18 {
print("成年人")
}
# if-else语句
if age >= 18 {
print("成年人")
} else {
print("未成年人")
}
# if-elif-else语句
score = 85
if score >= 90 {
grade = "A"
} elif score >= 80 {
grade = "B"
} elif score >= 70 {
grade = "C"
} elif score >= 60 {
grade = "D"
} else {
grade = "F"
}
print(f"成绩等级: {grade}")
条件表达式
# 三元运算符
age = 20
status = "adult" if age >= 18 else "minor"
# 链式条件表达式
score = 85
grade = (
"A" if score >= 90 else
"B" if score >= 80 else
"C" if score >= 70 else
"D" if score >= 60 else
"F"
)
# 空值合并
user_name = input_name or "Anonymous"
config_value = user_config.get("timeout") ?? 30
模式匹配
# match语句 (类似switch)
status_code = 404
match status_code {
200 => print("成功")
404 => print("未找到")
500 => print("服务器错误")
_ => print("未知状态码")
}
# 复杂模式匹配
data = {"type": "user", "id": 123, "name": "Alice"}
match data {
{"type": "user", "id": id, "name": name} => {
print(f"用户: {name} (ID: {id})")
}
{"type": "product", "id": id} => {
print(f"产品ID: {id}")
}
_ => print("未知数据类型")
}
# 条件模式匹配
value = 42
match value {
x if x < 0 => print("负数")
x if x == 0 => print("零")
x if x > 100 => print("大数")
x => print(f"正常数值: {x}")
}
3.2 循环结构
for循环
# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits {
print(f"我喜欢{fruit}")
}
# 遍历字典
person = {"name": "Alice", "age": 30, "city": "Beijing"}
for key, value in person.items() {
print(f"{key}: {value}")
}
# 遍历字符串
for char in "Hello" {
print(char)
}
# 范围循环
for i in range(5) {
print(i) # 0, 1, 2, 3, 4
}
for i in range(1, 6) {
print(i) # 1, 2, 3, 4, 5
}
for i in range(0, 10, 2) {
print(i) # 0, 2, 4, 6, 8
}
# 带索引的遍历
for index, value in enumerate(fruits) {
print(f"{index}: {value}")
}
# 并行遍历
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages) {
print(f"{name} is {age} years old")
}
while循环
# 基本while循环
count = 0
while count < 5 {
print(f"计数: {count}")
count += 1
}
# 条件循环
user_input = ""
while user_input != "quit" {
user_input = input("请输入命令 (quit退出): ")
if user_input != "quit" {
print(f"你输入了: {user_input}")
}
}
# 无限循环
while true {
data = fetch_data()
if data is null {
break
}
process_data(data)
sleep(1)
}
循环控制
# break语句
for i in range(10) {
if i == 5 {
break
}
print(i) # 0, 1, 2, 3, 4
}
# continue语句
for i in range(10) {
if i % 2 == 0 {
continue
}
print(i) # 1, 3, 5, 7, 9
}
# 嵌套循环控制
outer_loop: for i in range(3) {
for j in range(3) {
if i == 1 and j == 1 {
break outer_loop # 跳出外层循环
}
print(f"({i}, {j})")
}
}
循环推导式
# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
filtered_dict = {k: v for k, v in data.items() if v > 10}
# 集合推导式
unique_lengths = {len(word) for word in words}
# 生成器表达式
square_gen = (x**2 for x in range(1000000)) # 内存高效
3.3 函数定义与调用
基本函数
# 简单函数
func greet() {
print("Hello, World!")
}
greet() # 调用函数
# 带参数的函数
func greet_person(name: str) {
print(f"Hello, {name}!")
}
greet_person("Alice")
# 带返回值的函数
func add(a: int, b: int) -> int {
return a + b
}
result = add(3, 5)
print(result) # 8
# 多返回值
func divide_with_remainder(a: int, b: int) -> tuple[int, int] {
quotient = a // b
remainder = a % b
return quotient, remainder
}
q, r = divide_with_remainder(17, 5)
print(f"商: {q}, 余数: {r}") # 商: 3, 余数: 2
参数类型
# 默认参数
func greet_with_title(name: str, title: str = "先生") {
print(f"您好,{title}{name}!")
}
greet_with_title("张三") # 您好,先生张三!
greet_with_title("李四", "女士") # 您好,女士李四!
# 可变参数
func sum_all(*numbers: int) -> int {
return sum(numbers)
}
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字参数
func create_user(**kwargs: any) -> dict {
user = {
"name": kwargs.get("name", "Unknown"),
"age": kwargs.get("age", 0),
"email": kwargs.get("email", "")
}
return user
}
user = create_user(name="Alice", age=30, email="alice@example.com")
# 混合参数
func complex_function(
required: str,
optional: int = 10,
*args: any,
**kwargs: any
) {
print(f"必需参数: {required}")
print(f"可选参数: {optional}")
print(f"位置参数: {args}")
print(f"关键字参数: {kwargs}")
}
complex_function("test", 20, "extra1", "extra2", key1="value1", key2="value2")
函数注解与文档
func calculate_bmi(weight: float, height: float) -> float {
"""
计算身体质量指数(BMI)
Args:
weight: 体重(公斤)
height: 身高(米)
Returns:
BMI值
Raises:
ValueError: 当weight或height小于等于0时
Example:
>>> calculate_bmi(70, 1.75)
22.857142857142858
"""
if weight <= 0 or height <= 0 {
raise ValueError("体重和身高必须大于0")
}
return weight / (height ** 2)
}
# 查看函数文档
print(calculate_bmi.__doc__)
print(calculate_bmi.__annotations__)
3.4 高级函数特性
闭包
# 闭包示例
func create_multiplier(factor: int) -> func(int) -> int {
func multiply(x: int) -> int {
return x * factor # 访问外层变量
}
return multiply
}
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
# 计数器闭包
func create_counter() -> func() -> int {
count = 0
func increment() -> int {
nonlocal count
count += 1
return count
}
return increment
}
counter1 = create_counter()
counter2 = create_counter()
print(counter1()) # 1
print(counter1()) # 2
print(counter2()) # 1
装饰器
# 简单装饰器
func timer(func: callable) -> callable {
func wrapper(*args, **kwargs) {
start_time = time.now()
result = func(*args, **kwargs)
end_time = time.now()
print(f"{func.__name__} 执行时间: {end_time - start_time}秒")
return result
}
return wrapper
}
@timer
func slow_function() {
sleep(1)
return "完成"
}
result = slow_function() # 会显示执行时间
# 带参数的装饰器
func retry(max_attempts: int = 3) -> callable {
func decorator(func: callable) -> callable {
func wrapper(*args, **kwargs) {
for attempt in range(max_attempts) {
try {
return func(*args, **kwargs)
} catch Exception as e {
if attempt == max_attempts - 1 {
raise e
}
print(f"尝试 {attempt + 1} 失败,重试中...")
}
}
}
return wrapper
}
return decorator
}
@retry(max_attempts=3)
func unreliable_function() {
if random.random() < 0.7 {
raise Exception("随机失败")
}
return "成功"
}
# 类装饰器
class LogCalls {
func __init__(func: callable) {
self.func = func
self.call_count = 0
}
func __call__(*args, **kwargs) {
self.call_count += 1
print(f"调用 {self.func.__name__} 第 {self.call_count} 次")
return self.func(*args, **kwargs)
}
}
@LogCalls
func say_hello(name: str) {
print(f"Hello, {name}!")
}
say_hello("Alice") # 调用 say_hello 第 1 次
say_hello("Bob") # 调用 say_hello 第 2 次
高阶函数
# map函数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# filter函数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
# reduce函数
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# 自定义高阶函数
func apply_operation(data: list, operation: callable) -> list {
return [operation(item) for item in data]
}
func double(x: int) -> int {
return x * 2
}
result = apply_operation([1, 2, 3, 4], double)
print(result) # [2, 4, 6, 8]
Lambda函数
# 基本lambda
square = lambda x: x**2
print(square(5)) # 25
# 多参数lambda
add = lambda x, y: x + y
print(add(3, 4)) # 7
# 在高阶函数中使用lambda
data = [("Alice", 25), ("Bob", 30), ("Charlie", 20)]
sorted_by_age = sorted(data, key=lambda person: person[1])
print(sorted_by_age) # [("Charlie", 20), ("Alice", 25), ("Bob", 30)]
# 条件lambda
max_func = lambda a, b: a if a > b else b
print(max_func(10, 20)) # 20
3.5 递归函数
基本递归
# 阶乘函数
func factorial(n: int) -> int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
print(factorial(5)) # 120
# 斐波那契数列
func fibonacci(n: int) -> int {
if n <= 1 {
return n
}
return fibonacci(n - 1) + fibonacci(n - 2)
}
print(fibonacci(10)) # 55
# 优化的斐波那契(记忆化)
from functools import lru_cache
@lru_cache(maxsize=None)
func fibonacci_optimized(n: int) -> int {
if n <= 1 {
return n
}
return fibonacci_optimized(n - 1) + fibonacci_optimized(n - 2)
}
尾递归优化
# 尾递归阶乘
func factorial_tail(n: int, acc: int = 1) -> int {
if n <= 1 {
return acc
}
return factorial_tail(n - 1, n * acc)
}
# 尾递归斐波那契
func fibonacci_tail(n: int, a: int = 0, b: int = 1) -> int {
if n == 0 {
return a
}
return fibonacci_tail(n - 1, b, a + b)
}
树遍历递归
# 二叉树节点
class TreeNode {
func __init__(value: any, left: TreeNode? = null, right: TreeNode? = null) {
self.value = value
self.left = left
self.right = right
}
}
# 前序遍历
func preorder_traversal(node: TreeNode?) -> list {
if node is null {
return []
}
result = [node.value]
result.extend(preorder_traversal(node.left))
result.extend(preorder_traversal(node.right))
return result
}
# 中序遍历
func inorder_traversal(node: TreeNode?) -> list {
if node is null {
return []
}
result = []
result.extend(inorder_traversal(node.left))
result.append(node.value)
result.extend(inorder_traversal(node.right))
return result
}
# 计算树的深度
func tree_depth(node: TreeNode?) -> int {
if node is null {
return 0
}
left_depth = tree_depth(node.left)
right_depth = tree_depth(node.right)
return 1 + max(left_depth, right_depth)
}
3.6 异常处理
基本异常处理
# try-catch语句
try {
result = 10 / 0
} catch ZeroDivisionError as e {
print(f"除零错误: {e}")
} catch Exception as e {
print(f"其他错误: {e}")
} finally {
print("清理资源")
}
# 多种异常类型
try {
data = json.loads(user_input)
value = data["key"]
result = 100 / value
} catch json.JSONDecodeError {
print("JSON格式错误")
} catch KeyError {
print("缺少必需的键")
} catch ZeroDivisionError {
print("值不能为零")
} catch (TypeError, ValueError) as e {
print(f"类型或值错误: {e}")
}
自定义异常
# 自定义异常类
class ValidationError(Exception) {
func __init__(message: str, field: str? = null) {
super().__init__(message)
self.field = field
}
class AuthenticationError(Exception) {
pass
}
# 使用自定义异常
func validate_user(user_data: dict) {
if "email" not in user_data {
raise ValidationError("缺少邮箱字段", "email")
}
if "@" not in user_data["email"] {
raise ValidationError("邮箱格式无效", "email")
}
if len(user_data.get("password", "")) < 8 {
raise ValidationError("密码长度不足8位", "password")
}
}
try {
validate_user({"email": "invalid-email"})
} catch ValidationError as e {
print(f"验证错误: {e} (字段: {e.field})")
异常链和上下文
# 异常链
func process_file(filename: str) {
try {
with open(filename, "r") as file {
data = json.load(file)
} catch FileNotFoundError as e {
raise ProcessingError(f"无法处理文件 {filename}") from e
} catch json.JSONDecodeError as e {
raise ProcessingError(f"文件 {filename} 格式错误") from e
}
# 异常上下文管理
class ErrorContext {
func __init__(operation: str) {
self.operation = operation
}
func __enter__() {
return self
}
func __exit__(exc_type, exc_val, exc_tb) {
if exc_type is not null {
print(f"在执行 {self.operation} 时发生错误: {exc_val}")
}
return false # 不抑制异常
}
}
with ErrorContext("数据处理") {
# 可能出错的代码
risky_operation()
}
3.7 生成器和迭代器
生成器函数
# 简单生成器
func count_up_to(max: int) {
count = 1
while count <= max {
yield count
count += 1
}
}
# 使用生成器
for num in count_up_to(5) {
print(num) # 1, 2, 3, 4, 5
}
# 斐波那契生成器
func fibonacci_generator() {
a, b = 0, 1
while true {
yield a
a, b = b, a + b
}
}
# 获取前10个斐波那契数
fib_gen = fibonacci_generator()
fib_numbers = [next(fib_gen) for _ in range(10)]
print(fib_numbers) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# 文件行生成器
func read_lines(filename: str) {
with open(filename, "r") as file {
for line in file {
yield line.strip()
}
}
}
# 处理大文件而不占用太多内存
for line in read_lines("large_file.txt") {
process_line(line)
自定义迭代器
# 迭代器类
class Range {
func __init__(start: int, end: int, step: int = 1) {
self.start = start
self.end = end
self.step = step
}
func __iter__() {
return RangeIterator(self.start, self.end, self.step)
}
}
class RangeIterator {
func __init__(start: int, end: int, step: int) {
self.current = start
self.end = end
self.step = step
}
func __iter__() {
return self
}
func __next__() {
if self.current >= self.end {
raise StopIteration
}
value = self.current
self.current += self.step
return value
}
}
# 使用自定义迭代器
for i in Range(0, 10, 2) {
print(i) # 0, 2, 4, 6, 8
}
3.8 函数式编程特性
纯函数
# 纯函数示例
func add_pure(a: int, b: int) -> int {
return a + b # 无副作用,相同输入总是产生相同输出
}
# 非纯函数示例
counter = 0
func add_impure(a: int, b: int) -> int {
global counter
counter += 1 # 有副作用
return a + b + counter
}
# 避免副作用的函数
func process_data_pure(data: list) -> list {
# 不修改原始数据,返回新的数据
return [item * 2 for item in data]
}
original_data = [1, 2, 3, 4]
processed_data = process_data_pure(original_data)
print(original_data) # [1, 2, 3, 4] (未被修改)
print(processed_data) # [2, 4, 6, 8]
函数组合
# 函数组合
func compose(f: callable, g: callable) -> callable {
return lambda x: f(g(x))
}
func add_one(x: int) -> int {
return x + 1
}
func multiply_by_two(x: int) -> int {
return x * 2
}
# 组合函数
add_one_then_multiply = compose(multiply_by_two, add_one)
result = add_one_then_multiply(5) # (5 + 1) * 2 = 12
# 管道操作
func pipe(value: any, *functions: callable) -> any {
result = value
for func in functions {
result = func(result)
}
return result
}
result = pipe(5, add_one, multiply_by_two, add_one) # ((5 + 1) * 2) + 1 = 13
柯里化
# 柯里化函数
func curry_add(a: int) -> func(int) -> int {
return lambda b: a + b
}
add_five = curry_add(5)
result = add_five(3) # 8
# 通用柯里化装饰器
func curry(func: callable) -> callable {
func curried(*args, **kwargs) {
if len(args) + len(kwargs) >= func.__code__.co_argcount {
return func(*args, **kwargs)
}
return lambda *more_args, **more_kwargs: curried(
*(args + more_args),
**{**kwargs, **more_kwargs}
)
}
return curried
}
@curry
func multiply_three(a: int, b: int, c: int) -> int {
return a * b * c
}
# 部分应用
multiply_by_2_and_3 = multiply_three(2)(3)
result = multiply_by_2_and_3(4) # 2 * 3 * 4 = 24
本章小结
本章详细介绍了AI Script的控制结构和函数特性。通过学习本章,你应该:
- 掌握各种条件语句和循环结构的使用
- 理解函数的定义、调用和参数传递
- 了解高级函数特性如闭包、装饰器和高阶函数
- 掌握递归函数的编写和优化
- 学会异常处理的最佳实践
- 理解生成器和迭代器的概念
- 了解函数式编程的基本特性
这些控制结构和函数特性为编写复杂的AI Script程序提供了强大的工具。
练习题
- 编写一个递归函数计算目录中所有文件的总大小
- 实现一个装饰器来缓存函数的计算结果
- 创建一个生成器函数来逐行处理大型CSV文件
- 使用函数式编程风格实现一个数据处理管道
下一章:第四章:AI集成与机器学习