首页 > 编程语言 > 详细

【Python函数与模块】(5)函数中的使用技巧

时间:2020-04-07 22:43:28      阅读:85      评论:0      收藏:0      [点我收藏+]

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

 

【Python函数与模块】(5)函数中的使用技巧

原文:https://www.cnblogs.com/ac-chang/p/12656662.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!