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

@浙大疏锦行

相关推荐
猿界零零七3 小时前
pip install mxnet 报错解决方案
python·pip·mxnet
不只会拍照的程序猿5 小时前
《嵌入式AI筑基笔记02:Python数据类型01,从C的“硬核”到Python的“包容”》
人工智能·笔记·python
Jay_Franklin5 小时前
Quarto与Python集成使用
开发语言·python·markdown
Oueii6 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
2401_831824967 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf7 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
@我漫长的孤独流浪7 小时前
Python编程核心知识点速览
开发语言·数据库·python
宇擎智脑科技7 小时前
A2A Python SDK 源码架构解读:一个请求是如何被处理的
人工智能·python·架构·a2a
2401_851272997 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
vx_biyesheji00017 小时前
Python 全国城市租房洞察系统 Django框架 Requests爬虫 可视化 房子 房源 大数据 大模型 计算机毕业设计源码(建议收藏)✅
爬虫·python·机器学习·django·flask·课程设计·旅游