前 7 天,我们已经能用变量、判断、循环和数据结构完成小程序。但随着代码越来越长,一个新问题会出现:相同的逻辑被写了很多遍,修改起来也越来越麻烦。
函数就是解决这个问题的工具。
函数是一个有名字、可以反复调用的代码块。
使用 def 定义函数:
def say_hello():
print("你好,欢迎学习 Python!")
这段代码只是定义函数,并不会立即输出。需要主动调用:
say_hello()
say_hello()
函数名后面的括号表示“执行这个函数”。调用两次,就会输出两次。
二、为什么要使用函数
假设程序多次显示同一个菜单:
print("1. 添加记录")
print("2. 查看记录")
print("3. 退出程序")
可以把它整理成函数:
def show_menu():
print("1. 添加记录")
print("2. 查看记录")
print("3. 退出程序")
以后需要显示菜单时,只写:
show_menu()
这样做有三个好处:
三、参数:把数据交给函数
参数让同一个函数可以处理不同数据:
def greet(name):
print(f"你好,{name}!")
greet("Linda")
greet("小明")
定义函数时的 name 叫参数,调用函数时传入的 "Linda" 叫实参。
函数可以有多个参数:
def show_product(name, price):
print(f"商品:{name},价格:{price:.2f}元")
show_product("键盘", 299)
参数顺序必须与定义时保持一致。
四、return:把结果交还给调用者
print() 负责显示结果,return 负责把结果返回到函数外部。
def add(a, b):
result = a + b
return result
total = add(10, 20)
print(total)
可以直接简写:
def add(a, b):
return a + b
返回的结果还可以继续参与计算:
price1 = add(10, 20)
final_price = price1 * 2
函数执行到 return 后会立即结束,因此 return 后面同一层级的代码不会继续执行。
五、默认参数
可以为参数设置默认值:
def greet(name, message="欢迎回来"):
print(f"{name},{message}!")
greet("Linda")
greet("Linda", "今天也要加油")
没有传入 message 时使用默认值,传入后则使用新值。
带默认值的参数通常放在普通参数之后:
def greet(name, message="你好"):
pass
六、让每个函数只负责一件事
下面这个函数同时读取输入、计算和输出,职责太多:
def shopping():
price = float(input("单价:"))
quantity = int(input("数量:"))
print(price * quantity)
更清楚的写法是把计算单独拆出来:
def calculate_total(price, quantity):
return price * quantity
这样这个函数不依赖用户输入,也更容易重复使用和测试。
基础练习
- 1. 编写
say_hello(),输出一句问候语。 - 2. 编写
calculate_area(length, width),返回长方形面积。 - 3. 编写
is_even(number),返回一个数字是否为偶数。 - 4. 编写
format_price(price),返回保留两位小数的价格文字。 - 5. 编写带默认参数的
introduce(name, city="上海")。
今日项目:函数版购物结算器
def calculate_subtotal(price, quantity):
return price * quantity
def calculate_discount(subtotal, discount_rate):
return subtotal * discount_rate / 100
def show_result(product, subtotal, discount, final_price):
print("\n======== 结算结果 ========")
print(f"商品:{product}")
print(f"原价:{subtotal:.2f}元")
print(f"优惠:{discount:.2f}元")
print(f"实付:{final_price:.2f}元")
product = input("请输入商品名称:").strip()
price = float(input("请输入商品单价:"))
quantity = int(input("请输入购买数量:"))
discount_rate = float(input("请输入优惠比例:"))
subtotal = calculate_subtotal(price, quantity)
discount = calculate_discount(subtotal, discount_rate)
final_price = subtotal - discount
show_result(product, subtotal, discount, final_price)
查漏测试
- 3.
print() 与 return 有什么区别? - 4. 函数执行到
return 后还会继续运行吗?
学会函数后,代码不只是“能运行”,还开始变得容易阅读、修改和复用。