3,python基础之函数

---恢复内容开始---

函数:

函数:是带名字的代码块用于完成具体工作

函数的作用:

-合并重复

-测试方便

-修改方便

-打包

-映射

-偷懒

def function_name(s):
        statement(s)

#def 关键词
#s 参数可以有多个用,用逗号分隔
#function_name  函数名,小写字母下划线连接单词
#statement(s)代码块

几种函数参数用法:

1,:默认参数

import random
def choose_num(start,end=10):    #默认函数要放在非默认函数后面
        num = random.randint(start,end)
        return num    #返回值
choose_num(2,50) #调用函数

注意可变对象在默认值的特殊情况

#默认值只计算一次!注意列表当参数默认值
def f(a, L=[]):
        L.append(a)
        return L

print(f(1))
print(f(2))
print(f(5))

2.关键词参数(K=V)

def car(color, price="1000", user='de8gu'):
        print(f"{user}have a{color}'s car, prices is {price}yuan")

car('bule')  #使用默认参数
car("red",'90','hmm')#对应位置参数
car(color="blue",price="90")#使用关键词参数
car(price=90)#非默认参数必须,赋值

3.任意参数  能够·传递任意类型参数

# *args  **kwargs  :  args--->tuple 元组  **kwargs-->dict 字典
#*args
def car(*args): #加一个星号 参数 可以传入元组
      print(args)
      for k in args:
            print(k)

car("red", 10, "de8ugu") #这里传入的就是元组


#**dict
  
def car(**kw): #这里是两个星号,传入的就是字典类型
        for k,v in kw.items():
                    print(f"{k}::{v}")
#car("red",20,"de8ug")  #错误传入,上面定义的是字典类型
car(color="red",price=20,user="de8ug")  #传入字典类型,一一对应关系



#*args,**kwargs 所有类型都能传

def  car(color,price,*args,**kw): #什么类型都能传
     print("args":args)
     print("kw":kw)
     for k in args:
            print(k)
     for k,v in kw.items():
            print(f"{k}::{v}")

car("asd","T",coloe=red,price=100,user="de8gu")

直接传字典:

kw = {"color":"red","price":30} #先用一个字典,然后直接传、
def car(**kw):  #要有两星号参数才能接收到这个字典
    print(kw)
car(**kwargs)  #传的时候固定写法,加两个星号

kwargs = {color":"red","price":"de8gu"} #第二种方法传字典
def car(color="blue",price=99):
        print(color,price)

car(**kwargs)

需求:必须要函数传递某个参数

def car(color="blue",*,price): 固定写法加星号,星号后面的参数是必须要传递的参数
            print(color,price)
car(price=100) #必须写明谁是谁

lambda表达式,匿名函数

add = lambda  x:x+1
add(17)  

all_up_again= lambda s: s.strip().upper()
all_up_again('py')  #不被推荐写法



my_list = [1,2,3,4,5,6]  #找到列表里所有奇数,并返回一个新列表
def odd(*L):
    new_list = []
    for k in L:
         if k%2==1:
             new_lsit.append(k)
      return new_list
odd(*my_list)


lambda 写法


#filter 内置函数
#filter(lambda x: x%2 ==1,my_list)
#list(filter(lambda x: x%2 ==1,my_list))

函数注释与文档说明

def add(x,y)
    """add x and y together"""#函数功能说明
        return x+ y

def add(x:int,y:"这个随便") ->int:   #函数注释
     """add x and y together"""
      return x+y

add.__doc__  #返回文档说明
add.__annotations__  #返回函数中的注释内容

#pass 抢地盘,凑语法

def add():
     pass

2.作用域!

#变量作用域,在自己屋子干自己的事儿

#LEGB: Local, Enclosing, Global, Builtin

#翻译:本地(局部),封闭,全局,内置

x = 1 #全局变量

def add():
        x += 1  #局部变量赋值错误
        print(x)

add()
x = 99 #全局变量
def add():
        print(x)  # 直接使用全局变量

add()
error_lsit = [2,3,5]
def big_list():
       new_list = error_list   #先让error_list在局部作用有一个地盘
       new_list += [99]
       print(new_list)

big_list()

函数嵌套

函数是python里面的一级对象。可以用在任何地方,比如函数里面这个时候作用域属于封闭作用域

一级对象:

-在运行是创建

-能赋值给变量或数据结构

-能作为参数传给函数

-能作为函数的返回结果

def calc(x,y):
    def add(x,y):
        print("x+y:", x+y)
     def sub(x,y):
        print("x+y:",x-y)
     def mul(x,y):
         print("x*y:",x*y)

      add(x,y)
      sub(x,y)
      return mul

calc(2,5)
s = calc(3,5)   # 

s(5,7)

闭包(函数)

函数闭包,或者闭包函数,本质是一种函数,可以在运行后,依然存在自由变量,可以对闭包内的数据进行隐藏,避免使用全局变量

def hello():
    s = "de8ug"
    def say():
        nonlocal s  #global 不推荐使用
        s+='在干啥'
         print(s)
     return say
h = hello()
h()    

猜你喜欢

转载自www.cnblogs.com/chenlingxiang-bo-ke/p/9263651.html