Day32 PythonStudy

@浙大疏锦行

python 复制代码
import math

def calculate_circle_area(radius):
    """
    计算圆的面积
    
    参数:
    radius: 圆的半径
    
    返回:
    圆的面积,如果半径为负数则返回0
    """
    try:
        # 检查半径是否为负数
        if radius < 0:
            print(f"警告:半径为负数 ({radius}),返回0")
            return 0
        
        # 计算圆的面积
        area = math.pi * (radius ** 2)
        return area
    
    except TypeError:
        print(f"错误:参数类型不正确,应为数值类型,但传入的是 {type(radius).__name__}")
        return 0
    except Exception as e:
        print(f"发生未知错误:{e}")
        return 0
python 复制代码
calculate_circle_area(5)
python 复制代码
calculate_circle_area(0)
python 复制代码
calculate_circle_area(-1)
python 复制代码
def calculate_rectangle_area(length, width):
    # 检查半径是否为负数
    if length or width < 0:
        return 0
        
        # 计算面积
    area = length * width
    return area
python 复制代码
def calculate_average(*args):
    """
    计算平均值(静默版,返回0但不打印信息)
    """
    if len(args) == 0:
        return 0
    
    # 检查所有参数是否为数字
    for arg in args:
        if not isinstance(arg, (int, float)):
            return 0
    
    return sum(args) / len(args)
python 复制代码
def print_user_info(userid, **kwargs):
    """
    打印用户信息
    
    参数:
    userid: 必需的用户ID(位置参数)
    **kwargs: 额外的用户信息(关键字参数)
    
    功能:
    - 打印用户ID
    - 逐行打印所有额外的用户信息
    - 无返回值
    """
    # 打印用户ID
    print(f"用户ID: {userid}")
    
    # 检查是否有额外的信息
    if not kwargs:
        print("暂无额外信息")
    else:
        print("用户详细信息:")
        
        # 逐行打印所有额外信息
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    print()  # 添加空行使输出更清晰
python 复制代码
def describe_shape(shape_name, color="black", **kwargs):
    """
    格式化几何图形描述
    
    参数:
    shape_name: 必需,图形名称
    color: 可选,图形颜色,默认"black"
    **kwargs: 描述图形尺寸的关键字参数
    
    返回:
    格式化的描述字符串
    """
    # 构建尺寸描述部分
    if not kwargs:
        dimensions_desc = "with no specific dimensions"
    else:
        # 将尺寸参数转换为字符串列表
        dimension_parts = []
        for key, value in kwargs.items():
            dimension_parts.append(f"{key}={value}")
        
        # 组合所有尺寸描述
        dimensions_str = ", ".join(dimension_parts)
        dimensions_desc = f"with dimensions: {dimensions_str}"
    
    # 构建完整的描述字符串
    description = f"A {color} {shape_name} {dimensions_desc}."
    return description
python 复制代码
desc1 = describe_shape('circle', radius=5, color='red')
print(desc1)
desc2= describe_shape("rectangle",length=10,width=4)
print(desc2)
#输出:A black rectangle with dimensions: length=10,width=4

desc3 =describe_shape("triangle",base=6, height=8,color="blue")
print(desc3)
#输出:A blue triangle with dimensions: base=6, height=8
desc4=describe_shape("point",color="green")
print(desc4)
#输出:A green point with no specific dimensions.
相关推荐
孟健3 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞5 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽8 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程12 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪12 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook13 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python