Python函数基础:参数定义与灵活调用
实现圆形面积计算函数
创建一个名为 compute_circle_area 的函数,接收半径参数 radius,并返回对应的面积值。使用 math.pi 表示圆周率。
处理边界情况:若输入为负数或非数值类型,函数应返回0以确保健壮性。
import math
def compute_circle_area(radius):
if not isinstance(radius, (int, float)) or radius < 0:
return 0
return math.pi * radius ** 2
# 测试用例
test_cases = [5, 0, -1]
for r in test_cases:
print(f"半径 {r} 对应的面积: {compute_circle_area(r):.2f}")
编写矩形面积计算函数
定义 calculate_rect_area 函数,接受长度 length 与宽度 width 作为位置参数,计算并返回面积。
当任一维度小于零时,返回0。
def calculate_rect_area(length, width):
if length < 0 or width < 0:
return 0
return length * width
# 示例调用
print(calculate_rect_area(10, 4)) # 输出: 40
print(calculate_rect_area(-2, 5)) # 输出: 0
支持可变数量参数的平均值计算
设计 get_mean_value 函数,利用 *args 接收任意多个数值,返回其算术平均值。
无参数传入时返回0。
def get_mean_value(*numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
# 动态输入测试
while True:
user_input = input("请输入数字(空格分隔,输入 'quit' 退出): ").strip()
if user_input.lower() == 'quit':
break
try:
values = [float(x) for x in user_input.split()]
avg = get_mean_value(*values)
print(f"平均值: {avg:.2f}")
except ValueError:
print("输入格式错误,请输入有效数字!")
打印用户信息的多功能函数
实现 display_user_details 函数,要求必须提供 user_id,并可接受任意额外键值对信息。
函数将逐行输出用户ID及所有附加属性。
def display_user_details(user_id, **extra_info):
print(f"用户编号: {user_id}")
for key, value in extra_info.items():
print(f"{key}: {value}")
# 交互式测试
while True:
uid = input("输入用户编号(输入 'exit' 退出): ")
if uid.lower() == 'exit':
break
info = {}
while True:
k = input("添加字段名(输入 'end' 停止): ")
if k.lower() == 'end':
break
v = input(f"输入 {k} 的值: ")
info[k] = v
display_user_details(uid, **info)
生成结构化图形描述文本
定义 generate_shape_description 函数,用于生成包含颜色、形状和尺寸信息的完整描述。
shape_name为必填项。color默认为 "black"。- 通过
**kwargs收集尺寸参数。 - 若无尺寸信息,使用"无特定尺寸"描述。
def generate_shape_description(shape_name, color="black", **dimensions):
result = f"一个 {color} 的 {shape_name}"
if dimensions:
dim_str = ", ".join(f"{k}={v}" for k, v in dimensions.items())
result += f",具有以下尺寸: {dim_str}"
else:
result += ",无特定尺寸"
return result
# 使用示例
print(generate_shape_description("circle", radius=6))
print(generate_shape_description("rectangle", color="red", length=8, width=3))
print(generate_shape_description("triangle", color="green"))