Files
2025PY/day24/08-函数的总结.py
2025-05-22 16:50:44 +08:00

76 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 一、基础函数定义与调用
# 题目 1计算圆的面积
# 定义一个函数 calculate_area(radius),接收半径作为参数,返回圆的面积(使用公式:面积 = π * r²π 取 3.14)。
# 示例输入radius = 5
# 预期输出78.5
def calculate_area(radius):
pi = 3.14
return pi * radius ** 2
# 调用示例
result = calculate_area(5)
print(result) # 输出78.5
# 二、参数传递(位置参数、默认参数)
# 题目 2拼接姓名
# 定义函数 full_name(first, last, middle='')接收名、姓和中间名可选返回完整姓名格式first middle last中间名不存在时省略空格
# 示例输入 1first='John', last='Doe' → 输出:'John Doe'
# 示例输入 2first='Alice', last='Smith', middle='Mary' → 输出:'Alice Mary Smith'
def full_name(first, last, middle=''):
if middle: # 若middle不为空字符串
return f"{first} {middle} {last}"
else:
return f"{first} {last}"
# 调用示例
print(full_name('John', 'Doe')) # 输出John Doe
print(full_name('Alice', 'Smith', 'Mary')) # 输出Alice Mary Smith
# 三、返回值与多返回值
# 题目 3计算矩形的周长和面积
# 定义函数 rectangle_metrics(length, width),返回矩形的周长和面积。
# 示例输入length=4, width=3 → 输出:周长 14面积 12
def rectangle_metrics(length, width):
perimeter = 2 * (length + width)
area = length * width
return perimeter, area # 返回元组
# 调用示例
perimeter, area = rectangle_metrics(4, 3)
print(f"周长{perimeter},面积{area}") # 输出周长14面积12
# 四、可变参数(*args 和 kwargs
# 题目 4计算任意个数的平均值
# 定义函数 average(*nums),接收任意个数字参数,返回它们的平均值。若没有参数,返回 0。
# 示例输入 1average (1, 2, 3, 4) → 输出2.5
# 示例输入 2average (5, 10) → 输出7.5
# 示例输入 3average () → 输出0
def average(*nums):
if not nums: # 处理无参数情况
return 0
total = sum(nums)
return total / len(nums)
# 调用示例
print(average(1, 2, 3, 4)) # 输出2.5
print(average(5, 10)) # 输出7.5
print(average()) # 输出0