Python编程函数练习题
时间: 2025-04-22 11:58:17 浏览: 27
### Python 函数编程练习题
#### 定义简单函数
创建一个简单的加法器函数,接收两个参数 `num1` 和 `num2` 并返回其和。这有助于理解如何定义带有多个参数的函数以及执行基本运算[^3]。
```python
def add_numbers(num1, num2):
"""计算两个数相加"""
result = num1 + num2
return result
print(add_numbers(5, 7))
```
#### 使用默认参数值
编写一个具有默认参数值的函数来展示当未提供某些参数时程序的行为。此功能允许更灵活地调用函数而无需总是指定所有可能的输入项。
```python
def greet(name="Guest"):
"""向用户提供问候,默认称呼为'Guest'"""
print(f"Hello {name}!")
greet() # 输出 Hello Guest!
greet("Alice") # 输出 Hello Alice!
```
#### 实现带列表推导式的成本计算器
构建一个用于处理商品价格信息的成本计算器,它接受包含单位价格和数量的信息元组列表作为输入,并利用列表推导式快速完成总价计算工作[^4]。
```python
def calculate_total_cost(info_list):
"""
计算总费用
:param info_list: 商品详情表[(名称, 单价字符串, 数量字符串), ...]
:return: 总金额浮点数值
"""
total = sum(float(unit_price) * int(count) for _, unit_price, count in info_list)
return round(total, 2)
items = [("apple", "2.5", "3"), ("banana", ".8", "6")]
print(calculate_total_cost(items)) # 结果应接近于 9.30
```
#### 创建高阶函数
尝试实现更高层次的功能——即能够操作其他函数或将它们作为参数传递给另一个函数的能力。这里给出的例子是一个名为 `apply_operation` 的通用处理器,它可以应用于任何二元运算符函数上[^2]。
```python
from operator import mul, truediv
def apply_operation(func, a, b):
"""应用给定的操作到两个数字上"""
try:
outcome = func(a, b)
return f"The operation's result is {outcome}"
except Exception as e:
return str(e)
# 测试乘法与除法
print(apply_operation(mul, 4, 5)) # The operation's result is 20
print(apply_operation(truediv, 10, 2)) # The operation's result is 5.0
```
阅读全文
相关推荐

















