函数(function)是带名字的代码块,执行函数任务,即调用(call)函数。
仍然是一个门外汉的学习打卡~
1、定义函数:
使用关键字def告诉Python要定义一个函数,并且指向用户名def()后面的所有缩进是函数体。第二行是文档字符串(docstring)的注释,使用三个双引号,课包括多行。hello()这里只执行了一行代码。
#定义一个hello world函数
def hello():
""""显示HELLO WORD!"""
print("HELLO WORD!")
hello()
2、向函数传递信息:
message是形参(parameter),function是实参(argument)。
#调用函数指出本章的主题
def display_message(message):
"""指出本章的主题"""
print(f"\nThe object of this chapter is {message.title()}")
display_message('function')
3、传递实参:位置实参和关键字实参
3.1 位置实参:基于实参的位置进行关联,实参的顺序指向形参的顺序。调用函数直接再次使用函数即可。
#喜欢的书
def favorite_book(book_name, author):
"""指出我最喜欢的书名以及作者"""
print(f"\nOne of my favorite books is {book_name.title()}, its autor is {author.title()}.")
favorite_book('Harry Potter', 'J.K. Rowling')
favorite_book('The Hobbit', 'J. R. R. Tolkien')
3.2 关键字实参:无需考虑实参的顺序,在实参中名称和值被关联起来了。
#喜欢的书
def favorite_book(book_name, author):
"""指出我最喜欢的书名以及作者"""
print(f"\nOne of my favorite books is {book_name.title()}, its autor is {author.title()}.")
favorite_book(book_name='Harry Potter', author='J.K. Rowling')
favorite_book(author='J. R. R. Tolkien', book_name='The Hobbit')
4、形参的默认值:
4.1 若给形参指定了默认值,则不给形参指定实参时,Python将使用默认值。
#给形参设定默认值:描述喜欢的零食
def snack(taste, species = 'spicy strip'):
"""假设大多数人喜欢的零食是辣条,将零食种类的默认值设为Spicy strip"""
print(f"\nI like {species.title()}, especially {taste} ones.")
snack(taste = 'spicy')
这里运行结果为:
4.2 若给形参指定了默认值,同时给形参指定实参,Python将使用实参。
def snack(taste, species = 'spicy strip'):
"""假设大多数人喜欢的零食是辣条,将零食种类的默认值设为Spicy strip"""
print(f"\nI like {species.title()}, especially {taste} ones.")
snack(taste = 'spicy', species = 'humburger')
4.3 注意:如果函数里面只指定了一个实参,而函数定义时有两个形参,Python默认把那一个实参当做位置实参,因此这里的默认值形参放在了最后。若4.1中
def snack(taste, species = 'spicy strip'):
更改为:
def snack(species = 'spicy strip', taste):
那么调用函数仅仅给taste指定实参,就会报错,因为Python会当做那个实参是给species的,而taste没有指定~