通过上道习题,对函数有了一个基本的认识,下面这道习题中主要关注函数的入参。话不多说,代码来啦。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print(f"Man that's enough for a party!")
print(f"Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
print("OR, we can use variables from out script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
运行结果如下:
ex19中定义了一个名为cheese_and_crackers的函数,它接受2个参数,一个是cheese_count,另一个是boxes_of_crackers。
接下来一共调用了4次这个函数,每一次的传入参数为:
- 全部是常量,20和30;
- 全部都是变量,amount_of_cheese和amount_of_crackers;
- 全部是常量表达式,10 + 20和5 + 6;
- 全部是常量和变量结合的表达式,amount_of_cheese + 100和amount_of_crackers + 1000
所以说函数传入参数是非常多样的,你们需要慢慢品,仔细品!
小结
- 函数传入参数。