zoukankan      html  css  js  c++  java
  • Python基础(5)——函数

    函数

    在同一个.py文件中定义了两个同名函数,由于Python没有函数重载的概念,那么后面的定义会覆盖之前的定义,也就意味着两个函数同名函数实际上只有一个是存在的。

      定义  

    1 #函数定义
    2 def calc(x,y):
    3     res = x**y
    4     return res #返回函数执行结果
    5 
    6 calc() #调用函数

      关键参数

    正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。

    stu_register(22,name='Qian',course="python",)

      非固定参数

    若你的函数在定义时不确定用户想传入多少个参数,就可以使用非固定参数

     1 def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式
     2     print(name,age,args)
     3  
     4 stu_register("Alex",22)
     5 #输出
     6 #Alex 22 () #后面这个()就是args,只是因为没传值,所以为空
     7  
     8 stu_register("Jack",32,"CN","Python")
     9 #输出
    10 # Jack 32 ('CN', 'Python')
    View Code
    def add(*args):
        total = 0
        for val in args:
            total += val
        return total
    
    
    print(add())
    print(add(1))
    print(add(1, 2))
    
    #输出
    0
    1
    3

      

    还可以有一个**kwargs

     1 def stu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式
     2     print(name,age,args,kwargs)
     3  
     4 stu_register("Alex",22)
     5 #输出
     6 #Alex 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空
     7  
     8 stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")
     9 #输出
    10 # Jack 32 ('CN', 'Python') {'province': 'ShanDong', 'sex': 'Male'}
    View Code

      匿名函数

    1 #这段代码
    2 def calc(n):
    3     return n**n
    4 print(calc(10))
    5  
    6 #换成匿名函数
    7 calc = lambda n:n**n
    8 print(calc(10))
    View Code

      高阶函数

    一个函数可以接收另一个函数作为参数,或者返回值是一个函数,这种函数就称之为高阶函数。

    1 def add(x,y,f):
    2     return f(x) + f(y)
    3  
    4  
    5 res = add(3,-6,abs)
    6 print(res)
    View Code
  • 相关阅读:
    【leetcode】1215.Stepping Numbers
    【leetcode】1214.Two Sum BSTs
    【leetcode】1213.Intersection of Three Sorted Arrays
    【leetcode】1210. Minimum Moves to Reach Target with Rotations
    【leetcode】1209. Remove All Adjacent Duplicates in String II
    【leetcode】1208. Get Equal Substrings Within Budget
    【leetcode】1207. Unique Number of Occurrences
    【leetcode】689. Maximum Sum of 3 Non-Overlapping Subarrays
    【leetcode】LCP 3. Programmable Robot
    【leetcode】LCP 1. Guess Numbers
  • 原文地址:https://www.cnblogs.com/long5683/p/9299828.html
Copyright © 2011-2022 走看看