函数是一段 组织好的、可重复使用的、用来实现特定功能的 代码块。
例如:
- def make_juice():
- print('将猕猴桃去皮')
- print('将猕猴桃切块')
- print('将切碎的猕猴桃放进榨汁机')
- print('将果汁倒进杯子中')
- print('制作完成!')
参数类型:
根据不同的需求,Python 中的参数按传入方式分为两种:
参数名 = 值 的格式传入了参数例如:
- def print_foods(food1, food2, food3, food4):
- print(food1)
- print(food2)
- print(food3)
- print(food4)
-
- print_foods('小熊饼干', '果汁', '牛奶', '薯片')
-
- print_foods(food4='薯片', food3='牛奶', food1='小熊饼干', food2='果汁')
-
默认参数
- def record(name, height, weight, age=5):
- print('欢迎小朋友们!')
- print('姓名:', name)
- print('年龄:', age)
- print('身高:', height, 'cm')
- print('体重:', weight, 'kg')
-
- record('xback', 151, 48)
- def new_kids(kid1, kid2, kid3, kid4):
- # 多个值在 return 后并列,用英文逗号间隔开
- return kid1, kid2, kid3, kid4
-
- print(new_kids('小明', '小红', '小朋友', '小花'))
- # 输出:('小明', '小红', '小朋友', '小花')
在 Python 中变量分为两种: 全局变量 和 局部变量。
全局变量 在当前写的代码中一直起作用。全局变量 有效的范围,叫作 全局作用域。
局部变量 只在一定范围内有效,在范围外就无效了。
如果局部变量和全局变量名称相同,那函数内部会优先访问局部变量,外部只会访问全局变量。
- total_rent = 0
- def calc_rent(n, rent):
- # 原来的函数中 total_rent 只是局部变量
- # 与全局变量 total_rent 名称相同,但互不干扰
- # 所以要用 global 关键字将 total_rent 与之前的全局变量挂钩
- global total_rent
- total_rent = n * rent
-
- calc_rent(12, 3500)
-
- # 现在的 total_rent 仍是全局变量
- # 由于函数中的 global 关键字,函数中对 total_rent 的修改全局生效了
- print(total_rent)