07 Python函数进阶一(参数传递)

 

一、参数传递的方式

1、参数类型

         位置参数   (positional argument)

         关键词参数(keyword grgument)

2、参数传递方式

     (1)首先创建自定义函数:求梯形的面积

              def  trapezoid_area(base_up, base_down, height):
                    return 1/2 * (base_up + base_down) * height

     (2)第一种调用函数方式:

              trapezoid_area(1,2,3)

             参数1,2,3分别对应着参数base_up, base_down, height。

             这种传递参数的方式被称作为位置参数传递

     (3)第二种调用函数方式:

              trapezoid_area(base_up=1, base_down=2, height=3)

              每个参数名称后面赋予一个值,这种以名称作为一一对应的参数传递方式被称作为关键词参数传递

      (4)混合参数传递

              trapezoid_area(height=3, base_down=2, base_up=1)        # RIGHT!
              trapezoid_area(height=3, base_down=2, 1)                        # WRONG!
              trapezoid_area(base_up=1, base_down=2, 3)                     # WRONG!
              trapezoid_area(1, 2, height=3)                                             # RIGHT!

       (5)调用参数的省略问题

       print('  *',' * *','* * *','  |')

运行结果:
  *  * * * * *   |
      print('  *',' * *','* * *','  |',sep='\n')

运行结果:
       *
      * *
     * * *
       |

               注意两个语句的区别及输出结果的区别:

               第一个语句的sep参数没有,则传递的默认值,同一行显示。

               第二个语句的sep参数传递的是\n,则进行换行显示。

               又如求梯形面积函数定义如下:

              def  trapezoid_area(base_up, base_down, height=3):

                     return 1/2 * (base_up + base_down) * height

               则可以这样调用

              trapezoid_area(1, 2)            结果为:4.5

              trapezoid_area(1, 2,3)      结果为:4.5

              trapezoid_area(1, 2,2)      结果为:3.0

              注:定义函数时,可以为参数设定默认值,

                   若调用函数时没有传递有默认值的参数,则此参数使用默认值,

                   若调用函数时给有默认值的参数传递了其它值,则使用传递的值。

3、自定义函数应用


def text_create(name, msg):
    desktop_path = 'd:/python/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path,'w')
    file.write(msg)
    file.close()
    print('Done')
text_create('hello','hello world')
    

 

posted on 2020-02-17 18:07  神密探索  阅读(158)  评论(0)    收藏  举报

导航