day30函数专题1:函数定义和参数@浙大疏锦行

day30函数专题1:函数定义和参数@浙大疏锦行

python 复制代码
import math
def calculate_circle_area(radius):
    if(radius < 0):
        raise ValueError("Radius cannot be negative")
    return math.pi * radius * radius

# print(calculate_circle_area(5))
# print(calculate_circle_area(0))
# print(calculate_circle_area(-3))  # This will raise an exception

# 计算矩形面积函数
def calculate_rectangle_area(length, width):
    if length < 0 or width < 0:
        return 0
    return length * width

# 测试用例
print(calculate_rectangle_area(5, 3))   # 输出: 15
print(calculate_rectangle_area(0, 10))  # 输出: 0
print(calculate_rectangle_area(-2, 4))  # 输出: 0
print(calculate_rectangle_area(6, -1))  # 输出: 0

# 计算平均值函数
def calculate_average(*args):
    if len(args) == 0:
        return 0
    return sum(args) / len(args)

# # 测试用例
# print(calculate_average(1, 2, 3, 4, 5))  # 输出: 3.0
# print(calculate_average(10, 20))         # 输出: 15.0
# print(calculate_average())               # 输出: 0
# print(calculate_average(7))              # 输出: 7.0

# 打印用户信息函数
def print_user_info(user_id, **kwargs):
    print(f"用户ID: {user_id}")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# # 测试用例
# print_user_info(1001, name="张三", age=20, city="北京")
# print_user_info(1002)
# print_user_info(1003, email="test@example.com")

# 图形描述函数
def describe_shape(shape_name, color="black", **kwargs):
    desc = f"A {color} {shape_name}"
    if kwargs:
        dims = ", ".join([f"{k}={v}" for k, v in kwargs.items()])
        desc += f" with dimensions: {dims}."
    else:
        desc += " with no specific dimensions."
    return desc

# # 测试用例
# print(describe_shape("circle", radius=5))
# print(describe_shape("rectangle", "red", length=10, width=4))
# print(describe_shape("triangle"))
# print(describe_shape("ellipse", color="blue", a=3, b=2))

@浙大疏锦行

相关推荐
AI攻城狮11 分钟前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling14 分钟前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮3 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽4 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健19 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞21 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain