Python 的流程控制语法简洁。函数使用 def 定义,支持默认参数、关键字参数和可变参数。
本节要点
- if / elif / else 处理条件分支。
- for 可以遍历列表、字典、字符串等可迭代对象。
- 函数可以有多个返回值。
代码示例
def calc_price(price, count=1, discount=1.0):
total = price * count * discount
return round(total, 2)
for i in range(1, 4):
print(i, calc_price(99, i, 0.9))
def stats(nums):
return min(nums), max(nums), sum(nums) / len(nums)
print(stats([80, 90, 100]))