• Python编程入门-第五章 函数 -学习笔记


    第五章 函数

    一、调用函数 
    对于函数pow(x,y),它是内置在Python中的,提供计算x的y次方的功能。 
    其中pow是函数名,x和y是函数的两个参数,函数返回值是x的y次方。 
    而另外还有一些函数不提供返回值,只实现一些指定的功能,比如print函数。

    二、定义函数

    #自定义一个计算圆面积的函数
    import math
    def area(r):
        """Returns the area of a circle with
        the given radius.
        For example:
        >>>area(5.5)
        95.033177771091246
        """
        return math.pi*(r**2)
    

    上述代码中定义了一个计算圆面积的函数,函数名为area,半径r作为为参数。 
    *格式约定:python文档字符串通常用三引号标识文档字符串的开始和结束位置。对于上述自定义函数area可以通过print(area.__doc__)来查看函数的文档字符串。 
    *对于没有返回值的函数,默认返回为None,即:没有返回值。

    三、变量的作用域

    import math
    def dist(x,y,a,b):
      s=(x-a)**2+(y-b)**2
      return math.sqrt(s)
    def rect_area(x,y,a,b)
      width=abs(x-a)
      height=abs(y-b)
      return width*height

    对于上述示例中,在函数dist和rectarea中均有各自的局部变量x,y,a,b,除此之外,dist函数还有局部变量s,rect_area中还有width和height两个局部变量。局部变量仅在其所属函数中使用,函数结束时局部变量也会被自动删除。 
    *全局变量:在函数外面声明的变量称为全局变量,程序中的任何函数和代码都可以访问全局变量。

    name='Jack'
    def say_hello():
        print('Hello '+name+'!')
    def change_name(new_name):
        #实际运行中,我们可以发现全局变量name并没有发生改变
        #是因为函数体内的name变量为局部变量,调用时该局部变量屏蔽了全局变量
        name=new_name

    如果要针对上述的change_name()中访问并给全局变量name赋值,需要先通过关键字global声明使用的为全局变量。

    name='Jack'
    def say_hello():
        print('Hello '+name+'!')
    def change_name(new_name):
        
    #通过global声明函数体中使用的name为全局变量
    global name name=new_name

    四、使用main函数 
    在任何python程序中,通常都至少应该使用一个函数:main()。main()函数被认为是程序的起点。如下例:

    def main():
        pwd=input('please input the password:')
        if(pwd=='apple'):
           print('Logging on...')
        else:
           print('Icorrect password!')
        print('All Done!')

    如果在IDLE中运行上述程序时,并不会有什么输出,必须在提示符后输入main()来执行程序代码。

    五、函数的参数 
    1、按引用传递 
    向函数传递参数时,Python采用按引用传递的方式,即传参时,函数将使用新变量名来引用原始值。

    def add(a,b):
        return a+b
    x,y=3,4
    print(str(add(x,y)))

    x,y是全局变量,当调用函数add(x,y)时,实际上是把实参x,y的值分别传递给了函数的本次局部变量a,b,函数运行完毕返回值后a和b被系统销毁,而x和y并未受影响。 
    对于如下示例:

    def set1(x):
        x=1
    m=5
    set1(m)
    print(m)

    运行后发现m的值并没有变化(仍然是5),这里是因为函数set1运行时,只是把全局变量m的值传递给局部变量x,而m本身值没有发生变化。 

    2、给参数指定为默认值 
    如对于下例函数:

    def greet(name,greeting='Hello'):
        print(greeting,name+'!')
    greet('Bob')
    greet('Bob','Good morning')

    输出为:

    Hello Bob!
    Good morning Bob!

    这里发现,对于第二个参数,可以隐去,那调用时候会默认为函数定义时的方式;也可以显式写出第二个参数的常量值,这时运行后将用这个常量值替代定义时的默认值。 
    需要注意的是:带默认值的参数不能位于没有默认值的参数之前。 
    3、关键字参数

    def shop(where='store',what='pasta',howmuch='10 pounds'):
        print('I want you to go to the',where)
        print('and buy',howmuch,'of',what+'.')
    shop()
    shop(what='towels')
    shop(howmuch='a ton',what='towels',where='bakery')

    输出如下:

    I want you to go to the store
    and buy 10 pounds of pasta.
    I want you to go to the store
    and buy 10 pounds of towels.
    I want you to go to the bakery
    and buy a ton of towels.
    

    可以看出使用关键字参数的函数在特定情况下使用会十分方便,可以不指定参数,这样就是直接使用定义函数时的参数,也可以指定部分或全部参数重新改变输出。并且,关键字参数的顺序可以打乱。

    六、模块 
    首先,模块是一系列相关的函数和变量。 
    1、创建Python模块 
    要创建模块,可以建立一个单独的.py文件,在其中编写用于完成任务的函数。如下例是一个用于在屏幕上打印形状的简单模块:

    #shapes.py
    """A collection of functions
       for printing basic shapes
    """
    CHAR='*'
    def rectangle(height,width):
        """Prints a rectangle."""
        for row in range(height):
            for col in range(width):
                print(CHAR,end='')
            print()
    def square(side):
        """Prints a square."""
        rectangle(side,side)
    def triangle(height):
        """Prints a right triangle."""
        for row in range(height):
            for col in range(1,row+2):
                print(CHAR,end='')
            print()

    模块与常规Python程序之间唯一的区别就是用途不同:模块是一个由函数组成的工具箱,用于编写其他程序。因此,模块通常没有main()函数。当Python程序需要使用模块的时候,可以通过import来导入即可使用。

  • 相关阅读:
    Troubleshooting a Jedis Connection Pool Error
    com.mysql.cj.jdbc.exceptions.CommunicationsException
    springboot tomcat连接池
    Spring官方文档
    Troubleshooting-Spring-RestTemplate-Requests-Timeout
    Linux进程和端口命令总结
    Git及GitLab使用手册
    MySQL数据库命令大全
    两天时间,实现自己的 Promise
    vue-cli3.0搭建服务端渲染SSR
  • 原文地址:https://www.cnblogs.com/tsembrace/p/7111723.html
Copyright © 2020-2023  润新知