study_day03

#python-函数

  • 函数的创建与调用:
def exchange(a,b): #定义函数exchange
    a,b=b,a        #执行语句
    return a,b     #返回值
print(exchange(20,50))#调用函数
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
(50, 20)
  • 变长参数的传递:
###元组类型变长参数的传递:
def prt(*tuple):
    if len(tuple)==0:#添加*号声明参数为元组
        print("空值")
    else:
        for i in tuple:
            print(i,end=" ")

prt(81,56,65,66)
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
81 56 65 66 

###字典类型变长参数的传递:
def tianya(*tup,**dic):
    if len(tup)==0:
        print("元组值为空")
    else:
        for i in tup:
            print(i,end=" <>")
    if len(dic)==0:
        print("空字典")
    else:
        print("\n")
        for a in dic:
            print("%s键对应的值为%s",(a,dic[a]),end=" ")
tianya(1,5,68,78,l=10,y=33,d=2)
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
1 <>5 <>68 <>78 <>

%s键对应的值为%s ('y', 33) %s键对应的值为%s ('l', 10) %s键对应的值为%s ('d', 2) 
  • 高阶函数:
    理解:在我看来是将一个函数当作对象,将其实例化后,把对象以参数的形式传递给函数:

def add(a,b):
    pass
    return a+b
def fddd(a,b):
    pass
    return a-b
def fun(a,b,f):
    return f(a,b)
ad=add
fd=fddd
a,b=23,55
print(fun(a,b,ad))
print(fun(a,b,fd))
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
78
-32
  • 匿名函数:
    使用lambda表达式来创建
    简化函数的调用过程
 funct=lambda a,b:a+b
print(funct(58,25))
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
83
  • 函数的递归
    【例】求阶乘:
def jiechen(n):
    if n==1:
        return 1
    else:
        return n*jiechen(n-1)
a=int(input("请输入"))
print(jiechen(a))
>>>
E:\Pycharmworkplace\untitled\venv\Scripts\python.exe "E:/Pycharmworkplace/untitled/studytest/study 03.py"
请输入8
40320

================================================

猜你喜欢

转载自blog.csdn.net/qq_40265485/article/details/83155267