zoukankan      html  css  js  c++  java
  • 八、函数

    一、内置函数

    1、如何查看内置函数的定义:help(print)

    2、函数的作用

    1)功能性

    2)隐藏细节

    3、避免编写重复的代码

    3、常见的内置函数

    print() 

    round()

    二、自定义函数

    1)先定义后使用

    2)自定义的函数名不能和python的内置函数同名

    3)参数可以为空或多个

    4)可以无返回,返回None,返回单个结果,返回多个结果

    无返回=返回None

    三、多个返回值的情况

    1、定义

    def function(parametor_list):

      ...

      return res1,res2

    2、调用

    r=function(parametor_list)

    r是元组类型,用多个变量接收

    res1,res2=function(parametor_list)

    四、序列解包与链式赋值

    1、序列解包

    把一个元组(包)拆成一个序列值,并用多个变量接收。即一次给多个变量赋多个值,基本方法就是一次性将一个元组赋值给多个变量。

    注意:变量个数和元组个数要相等

    d=tuple(1,2,3)

    a,b,c=d

    等价于

    a,b,c=1,2,3

    等价于

    a=1

    b=2

    c=3

    2、链式赋值:同时对几个变量进行赋值

    以下三种代码等价

    a=1

    b=1

    c=1

    a,b,c=1,1,1

    a,b,c=1

    a,b,c=1称为链式赋值

    五、必须参数与关键字参数

     1 # coding=utf-8
     2 
     3 # 定义
     4 def add(x, y):
     5     # x,y是必须参数
     6     res = x + y
     7     return res
     8 
     9 
    10 # 调用
    11 c = add(1, 2)
    12 print(c)
    13 
    14 d = add(y=1, x=2)  # y=1,x=2称为关键字参数
    15 print(d)

    必须参数:在函数的参数列表中定义的参数,调用时按顺序传入

    关键字参数:调用时明确实参、形参的对应关系,即形参=实参,可不考虑顺序。

    区别:调用时输入参数的格式

    六、默认参数

     1 #coding=utf-8
     2 
     3 #不使用默认参数
     4 # def print_student_files(name,gender,age,college):
     5 #     print('我叫'+name)
     6 #     print('我今年'+str(age)+'岁')
     7 #     print('我是'+gender+'生')
     8 #     print('我在'+college+'上学')
     9 
    10 #使用默认参数
    11 def print_student_files(name,gender='',age=9,college='人民路小学'):
    12     print('我叫'+name)
    13     print('我今年'+str(age)+'')
    14     print('我是'+gender+'')
    15     print('我在'+college+'上学')
    16 
    17 # #默认参数必须放在参数列表最后,否则报错SyntaxError: non-default argument follows default argument
    18 # def print_student_files(name,gender='男',age=9,college):
    19 #     print('我叫'+name)
    20 #     print('我今年'+str(age)+'岁')
    21 #     print('我是'+gender+'生')
    22 #     print('我在'+college+'上学')
    23 
    24 
    25 print_student_files('鸡小萌','',8,'人民路小学')
    26 print_student_files('小明')
    27 print_student_files('李雷')
    28 print_student_files('韩美美','',8,)
    29 print_student_files('王强')
    30 print_student_files('鸡小萌',age=8)
    31 #如下传参不允许
    32 print_student_files('果果',8)#会按顺序将8作为gender参数传入
    33 
    34 print_student_files('鸡小萌',gender='',8,college='人民路小学')#必须参数不能放在关键字参数后面

    注意:

    1、定义时:默认参数必须放在必须参数后面

    2、调用时:关键字参数必传放在必须参数后面

  • 相关阅读:
    Can't remove netstandard folder from output path (.net standard)
    website项目的reference问题
    The type exists in both DLLs
    git常用配置
    Map dependencies with code maps
    How to check HTML version of any website
    Bootstrap UI 编辑器
    网上职位要求对照
    Use of implicitly declared global variable
    ResolveUrl in external JavaScript file in asp.net project
  • 原文地址:https://www.cnblogs.com/loveapple/p/9375862.html
Copyright © 2011-2022 走看看