• Python 学习笔记11 函数


    函数其实一段带名字的代码段,我们可以根据代码段,重复执行某一段代码段,或者有条件的执行某一段代码段。

    将一段代码定义成函数后,我们可以很方便的根据自己的需求,随时调用该代码段。遇到需求变化的时候,只需要修改该函数,就可以满足需求,不需要到处修改特定的代码。

    比如我们定义一个print hello的函数:

    def say_hello():
        print("Hello!")
    
    say_hello()
    '''
    Hello!
    '''

    我们可以看到,我们使用def来定义函数, 以冒号结尾。 输入回车后,ide会自动缩进,缩进后的代码就是函数的定义体。定义完函数体后,我们通常空一行表示定义完函数。

    我们直接输入函数名,即可调用函数。

    我们还可以向函数传递“消息”,在编程语言中我们称之为参数。比如我们修改函数,可以向其传递一个人名,并输出想要语句。

    def say_hello(name):
        print(name + ", Hello!")
    
    say_hello('Ralf')
    '''
    Ralf, Hello!
    '''

    通过上面代码,我们可以看到,我们重新修改了函数,增加了一个参数 name, 修改了函数体。这样我们可以根据自己的需要,向函数传递消息,并输出想要的结果。

    函数定义中的参数,我们通常称之为 形参,比如上述例子中的变量name, 这个变量只在函数定义中使用,并不具有实际的值。我们在调用函数时,传递的消息或者说变量,我们称之为实参,是我们“实际“上想要使用的参数或者数值,变量。

    通常情况下,我们必须按照事先定义好的参数,依次传递给函数体,才能正确得出想要的结果。

    def say_hello(name, city):
        print(name + ", Welcome to " + city + "!" )
    
    say_hello('Ralf', "Shanghai")
    ''' Ralf, Welcome to Shanghai! '''
    def say_hello(name, city):
        print(name + ", Welcome to " + city + "!" )
    
    say_hello('Shanghai', "Ralf")
    ''' Shanghai, Welcome to Ralf! '''
    def say_hello(name, city):
        print(name + ", Welcome to " + city + "!" )
    
    say_hello('Ralf')
    ''' Traceback (most recent call last): File "D:/PythonStudy/test.py", line 31, in <module> say_hello('Ralf') TypeError: say_hello() missing 1 required positional argument: 'city' '''

    我们可以使用关键字的形式来规避上面例子中出现的错误,即在调用函数时,使用 形参 = value的方式来调用函数:

    def say_hello(name, city):
        print(name + ", Welcome to " + city + "!" )
    
    say_hello(city = "Shanghai", name = 'Ralf')
    '''
    输出:
    Ralf, Welcome to Shanghai! '''

    在定义函数时,我们也可以定义一些参数默认值,这样在调用,如果给了实参,函数就使用实参,没有给值,就是用默认值。

    def say_hello(name, city = "Shanghai"):
        print(name + ", Welcome to " + city + "!" )
    
    # 使用默认值
    say_hello("Ralf")
    
    #使用实际值
    say_hello("Rachel", "Beijing")
    ''' 输出: Ralf, Welcome to Shanghai! Rachel, Welcome to Beijing! '''

    返回值:

    函数不仅可以接受外部传送的变量参数,也可以输出一个返回值给调用者。

    def say_hello(name, city = "Shanghai"):
        return name + ", Welcome to " + city + "!"
    
    
    out_message = say_hello("Rachel", "Beijing")
    print(out_message)
    
    '''
    输出:
    Rachel, Welcome to Beijing!
    '''

     返回一个列表:

    def born_city(name, city = "Shanghai"):
        return [name, city]
    
    out_message = born_city("Rachel", "Beijing")
    print(type(out_message))
    print(out_message)
    
    '''
    输出:
    <class 'list'>
    ['Rachel', 'Beijing']
    '''

    返回一个字典:

    def born_city(name, city = "Shanghai"):
        return {'name': name, 'city': city}
    
    out_message = born_city("Rachel", "Beijing")
    print(type(out_message))
    print(out_message)
    
    '''
    输出:
    <class 'dict'>
    {'name': 'Rachel', 'city': 'Beijing'}
    '''

    传递任意数量的实参,有时候我们不确定,实际参数有几个,可以能是一个也可能是多个,要怎么定义哪。我们可以在形参前面加一个星号,表示这个参数可以是多个:

    def say_hello(*names):
        print(names)
    
    out_message = say_hello("Rachel", "Ralf", "Terry")
    print(out_message)
    
    '''
    输出:
    ('Rachel', 'Ralf', 'Terry')
    '''

    注意函数返回了一个元组,即便函数只输入一个参数,返回的也是一个元组。

    结合实参和任意数量的实参:

    def say_hello(words, *names):
        for name in names:
            print(words + ", " + name)
    
    out_message = say_hello("hello", "Rachel", "Ralf", "Terry")
    print(out_message)
    
    '''
    输出:
    hello, Rachel
    hello, Ralf
    hello, Terry
    '''

    使用任意数量的关键字实参。有时候我们需要接受任意数量的实参,但是不知传递给函数的会是什么样的信息。在这种情况下,我们可以将函数编写成接受任意数量的 键值对,即字典的形式。方式为加两个冒号 **dict:

    def pepole_info(name, sex, **others):
        print(name + ": "+ sex )
        for key, value in  others.items():
            print(key + ": " + value)
    
    out_message = pepole_info("Ralf", "male", height = "175", hobby = "football")
    print(out_message)
    
    '''
    输出:
    Ralf: male
    height: 175
    hobby: football
    '''
  • 相关阅读:
    漫谈五种IO模型
    jvm调优-命令大全(jps jstat jmap jhat jstack jinfo)
    Intellij IDEA 插件开发秘籍
    二进制
    java程序员必知的 8大排序
    Redis常见问题
    BitMap位图
    编程思想
    Final修饰的字段是否可以通过反射设置值
    ORACLE 11g ORA-20000: Unable to analyze TABLE "AA"."CMP3$87651", insufficient privileges or does not exist
  • 原文地址:https://www.cnblogs.com/wanghao4023030/p/10747072.html
Copyright © 2020-2023  润新知