1. 设置参数默认值
# 1. 设置参数默认值,只需在形参后添加 “ =具体值 ” 即可 def cal_exchange_rate(amt, source, target = "USD"): if source == "CNY" and target == "USD": # 货币比为:6.7516 : 1 return amt / 6.7516 elif source == "CNY" and target == "EUR": # 货币比为:7.7512:1 return amt / 7.7512 print(cal_exchange_rate(100, "CNY")) # 输出:14.811303987203035 print(cal_exchange_rate(100, "CNY", "EUR")) # 输出:12.901228196924347
2. 关键字传参
# 2. 以形参形式传参(关键字传参) hr:心率 hbp:血压高压 lbp:血压低压 glu:血糖 # 建议:遇到多个形参时,建议封装至字典中 def health_check(name, age, height, weight, hr, hbp, lbp, glu): print("您的身体状况良好") # 调用时前面加上形参,可读性好,不必完全按照顺序来 health_check(name = "张三", age = 20, height=178, weight=74, glu=20, hr=70, hbp=120, lbp=70 )
3. 混合形式传参
# 3. 混合形式传参(2的扩展):* 代表之后的所有参数必须使用关键字传参 def health_check(name, age, *, height, weight, hr, hbp, lbp, glu): print("您的身体状况良好") health_check("张三", 20, height=178, weight=74, glu=20, hr=70, hbp=120, lbp=70 )
4. 序列传参
# 4. 序列传参 def cal(a, b, c): return (a + b) * c lst = [1, 5, 10] print(cal(*lst)) # 输出:60
5. 字典传参
# 2. 字典传参 def health_check(name, age, height, weight, hr, hbp, lbp, glu): print(name) print(age) print(height) print(weight) print("您的身体状况良好") params = {"name":"张三", "age":20, "height":178, "weight":74, "glu":20, "hr":70, "hbp":120, "lbp":70} health_check(**params) # 输出: # 张三 # 20 # 178 # 74 # 您的身体状况良好
6. 返回值包含多个数据
# 3. 返回值包含多个数据 def get_detail_info(): dict1 = { "employee":[ {"name": "张三", "salary": 2000}, {"name": "李四", "salary": 3000} ], "device":[ {"id": "88323", "title": "xxx笔记本"}, {"id": "88234", "title": "xxx台式机"} ], "asset": [{}, {}], "project": [{}, {}] } return dict1 print(get_detail_info()) # 输出:{‘employee‘: [{‘name‘: ‘张三‘, ‘salary‘: 2000}, {‘name‘: ‘李四‘, ‘salary‘: 3000}], ‘device‘: [{‘id‘: ‘88323‘, ‘title‘: ‘xxx笔记本‘}, {‘id‘: ‘88234‘, ‘title‘: ‘xxx台式机‘}], ‘asset‘: [{}, {}], ‘project‘: [{}, {}]} d = get_detail_info() # 获取张三的工资信息 sal = d.get("employee")[0].get("salary") print(sal) # 输出:2000
原文:https://www.cnblogs.com/ac-chang/p/12656662.html