python3.7入门系列八 函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bowei026/article/details/89935929

函数是具有名字的一段可重复使用的代码块
定义函数使用关键字 def
>>> def hello():
...     print('hello')
...
>>> hello()
hello

函数的参数
>>> def hello(name):
...     print('hello, ' + name)
...
>>> hello('Tom')
hello, Tom

其中,定义hello函数时的参数name是形参,调用函数hello('Tom') 时的'Tom'是实参

位置实参
位置实参就是按函数定义时形参的位置顺序传递,如
>>> def hello_person(name, age):
...     print(name + ' is ' + str(age))
...
>>> hello_person('Tom', 18)
Tom is 18
如果不按顺序传递那么就可能发生语法报错或者程序的执行与预期不一致,如
>>> hello_person(18, 'Tom')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in hello_person
TypeError: unsupported operand type(s) for +: 'int' and 'str'
所以,位置实参的顺序特别重要,顺序错了会导致严重后果

关键字实参
>>> hello_person(name='Tom', age=18)
Tom is 18
>>> hello_person(age=18, name='Tom')
Tom is 18
因为通过关键字指定了实参的名称,所以顺序对于关键字实参不重要

默认值
函数定义时可以给形参指定默认值,当函数调用时没有给该参数传递值时,该参数将使用默认值
>>> def say_person(name, age=18):
...     print(name + ' is ' + str(age))
...
>>> say_person('Tom')
Tom is 18
这里没有传递参数age的值,因此使用了默认值18
对于没有默认值的参数,则必须提供实参的值,可以是位置实参,也可以是关键字实参
>>> say_person(name='Tom')
Tom is 18
 

返回值
def get_full_name(first_name, last_name):
    return first_name + last_name


name = get_full_name('张', '三')
print(name)
name = get_full_name('李', '四')
print(name)

以上代码运行后输出
张三
李四

函数可以有参数、返回值,能反复多次调用

返回字典
def get_name_dict(first_name, last_name):
    dict = {}
    dict['first_name'] = first_name
    dict['last_name'] = last_name
    #或者 return {'first_name' : first_name, 'last_name' : last_name}
    return dict


dict = get_name_dict('张', '三')
print(dict)
运行输出:
{'first_name': '张', 'last_name': '三'}

list做参数
def hello(fruits):
    for fruit in fruits:
        print('hello, ' + fruit)


fruits = ['apple', 'banana', 'pear']
hello(fruits)
运行输出:
hello, apple
hello, banana
hello, pear

修改参数的值(引用传值)
def change(fruits):
    fruits.append('watermelon')


fruits = ['apple', 'banana', 'pear']
change(fruits)
print(fruits)
运行输出:
['apple', 'banana', 'pear', 'watermelon']

不让改变参数
animals = ['dog', 'cat', 'pig']
change(animals[:])
print(animals)
运行输出:
['dog', 'cat', 'pig']
这里的animals[:] 是复制了一个对象,传给change函数并不是animals对象自己,而是一个复制副本

任意个数的参数
def out(*fruits):
    print(type(fruits))
    for fruit in fruits:
        print(fruit)


out('apple', 'banana', 'pear')
运行输出:
<class 'tuple'>
apple
banana
pear
可见函数out接到的参数类型是一个元组

传递任意个数的关键字参数
def out2(**person):
    print(type(person))
    for key, value in person.items():
        print(key + " : " + str(value))


out2(name='Tom', age=18)
运行输出:
<class 'dict'>
name : Tom
age : 18
 

Python 自带了很多内建函数,很多都是需要掌握的,访问地址  https://docs.python.org/3/library/functions.html

本文内容到此结束,更多内容可关注公众号和个人微信号:

猜你喜欢

转载自blog.csdn.net/bowei026/article/details/89935929