python函数基本概念

#函数的作用和定义,理解函数中的参数传递,实际参数,形式参数,
#理解函数的返回值,接受函数的返回值,
#实现具有特定功能的代码  预支了很多的内置函数
#函数的定义语法  函数用于代码的重用
#参数就是函数的输入数据更具参数的而不同执行不同的代码
def  print_verse(verse_name,is_show_title,is_show_dynasty):#形式参数  约束参数是如何使用的
    if verse_name == "静夜思":
        if is_show_title == True:
            print("静夜思——李白")
        if is_show_dynasty == True:
            print("唐朝")
        print("床前明月光")
        print("疑是地上霜")
        print("地上鞋两双")
    elif verse_name == "康桥":
        if is_show_title == True:
            print("康桥")
        if is_show_dynasty == True:
            print("民国")
        print("轻轻的我来了")
        print("挥一挥手不带走一片云彩")
print_verse("静夜思",True,True)#调用函数,实际参数 要和形参格式相同
#print_verse("康桥")

#函数的返回值
def calc_exchange_rate(amt,source,target):
    if  source == 'CNY' and target == 'USD':
        result = amt/6.7516
        return  result  #中断执行返回数值
r = calc_exchange_rate(100,'CNY','USD')
print(r)

#函数的使用技巧
#设置参数的默认值
#在形参中设置形参的默认值,此时在实参中可以不传递参数

#以形参形式传形参
def health_check(name,age,*,height,weight):#*之后必须用关键字传参
    print('身体健康')
health_check(name='李',height=178,age=23,weight=50)#此时顺序可以打乱

#函数的使用技巧-2
#序列传参
def calc(a,b,c):
    return (a+b)*c
l = [1,2,10]#生成一个列表
print(calc(*l))#注意*号

#字典传参
param = {'a':1,'b':2,'c':3}
print(calc(**param))#注意两个*号键

#返回值包含多个数据
def get_datail_info():
    dict1 = {
        'employee':[
            {'name':'张三','salary':1800},
            {'name':'李四','salary':2000}
        ],
        'device':[
            {'id':'12345','title':'笔记本'},
            {'id':'67890','title':'台式机'}
        ]
    }
    return  dict1
print(get_datail_info())
d=get_datail_info()
sal=d.get('employee')[0].get('salary')#字典-》列表-》字典 找到对应的数据
print(sal)

猜你喜欢

转载自blog.51cto.com/10805472/2457543