• day9 函数


      函数基本格式

     1 def test(x):  # x 为形参
     2     """
     3         2*x+1
     4         :param x:整型数字
     5         :return: 返回
     6     """
     7     y=2*x+1    # 运算过程 
     8     return  y  # 返回结果:返回值
     9 print(test)
    10 b = test(3)  # 代入实参运行函数进行计算
    11 print( b )    # 得到返回值并打印出来

      

      参数可以不带的函数

     1 def test():
     2     """
     3         2*x+1
     4         :param x:整型数字
     5         :return: 返回
     6     """
     7     x = 3
     8     y=2*x+1
     9     return     y
    10 b = test()
    11 print( test())

      

       形参,实参的对比

    1 def calc(x,y):     # 形参,只在函数内部有效,函数运算完就释放掉了
    2     res = x**y
    3     return res
    4 c = calc(a,b)        # 实参,函数外的真正开辟了内存的参数
    5 print(c)


    位置参数,一一对应,缺一不可
    1 def test(x,y,z):
    2     print(x)
    3     print(y)
    4     print(z)
    5 test(1,2,3)


    关键字参数,无需一一对应,缺一不可
    1 def test(x,y,z):
    2     print(x)
    3     print(y)
    4     print(z)
    5 test(y=1,z=2,x=3)


    位置参数必须在关键字参数左边,参数不能空,可能来回赋值就乱了
    1 def test(x,y,z):
    2     print(x)
    3     print(y)
    4     print(z)
    5 # test(1,z=2,3)       # 报错
    6 # test(1,3,y=3)       # 报错


    默认参数,定义初始参数,但是如果被赋值则取消默认参数
    1 def handle(x,type=None):
    2     print(x)
    3     print(type)
    4 handle("hello")
    5 handle("hello",type="sqskl")
    6 handle("hello","sqskl")

     
    参数组: * 列表 ** 字典
     1 def  test (x,*args):
     2 # 传多个不晓得会多少或者以后做扩展的时候,用*args表示接受列表
     3 # 或者**kwargs接受字典
     4     print(x)
     5     print(args)
     6     print(args[3])
     7 test(1,2,3,4,5,6)
     8 test(1,[1,2,3,4,5])        # 位置参数的形式传参,不论你是什么列表字典都当做一个元素来传
     9 test(1,*[1,2,3,4,5])        # 若不想要他作为一个整体元素,列表加* ,字典加** ,可以将内容独立做元素
    10 test(1,y=2,z=3,z=6)            #一个参数不能传两次 # 直接提示报错标红了
    1 def  test (x,*args,**kwargs):
    2 # 两者混用的时候,**kwargs必须放在最后面,不然会违背位置参数必须放在关键字参数左边的原则
    3     print(x)
    4     print(args,args[-1])
    5     print(kwargs,kwargs["y"])
    6 test(1,11,111154546,123,y=3,z=4)
    7 test(1,*[11,111154546,123],**{"y":3,"z":4})
    8 # 列表参数传递给*args用元祖方式进行传递
    9 # 关键字参数传递给**kwargs 用字典的方式传递

  • 相关阅读:
    configure: error: HTSlib development files not found
    configure: error: htscodecs submodule files not present.
    如何给虚拟机的磁盘动态扩容
    关闭anaconda3 默认自动启动的命令
    github.com[0: 192.30.255.113]: errno=Connection refused
    centos7 中安装java8
    centos7 中manta软件的安装
    168张图,万字长文,手把手教你开发vue后台管理系统
    maven打包excel乱码
    面渣逆袭:Java集合连环三十问
  • 原文地址:https://www.cnblogs.com/shijieli/p/9687042.html
Copyright © 2020-2023  润新知