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

@浙大疏锦行

相关推荐
梨子串桃子_15 小时前
推荐系统学习笔记 | PyTorch学习笔记
pytorch·笔记·python·学习·算法
文言一心16 小时前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
诗词在线17 小时前
中国古代诗词名句按主题分类有哪些?(爱国 / 思乡 / 送别)
人工智能·python·分类·数据挖掘
高锰酸钾_17 小时前
机器学习-L1正则化和L2正则化解决过拟合问题
人工智能·python·机器学习
天天睡大觉17 小时前
Python学习11
网络·python·学习
智航GIS17 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
写代码的【黑咖啡】18 小时前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
抠头专注python环境配置18 小时前
解决Windows安装PythonOCC报错:从“No module named ‘OCC’ ”到一键成功
人工智能·windows·python·3d·cad·pythonocc
华研前沿标杆游学18 小时前
2026年华研就业实践营|走进字节跳动,解锁科技行业职业新航向
python