Day 4 of Learning Python

在这里插入图片描述

Chapter 8 函数

8.1 定义函数

def greet_user():"""显示简单的问候语"""print("Hello!")
❹ greet_user()

❶处的代码行使用关键字def 来告诉Python你要定义一个函数。这是函数定义 ,向Python指出了函数名,还可能在括号内指出函数为完成其任务需要什么样的信息。在这里,函数名为greet_user() ,它不需要任何信息就能完成其工作,因此括号是空的(即便如此,括号也必不可少)。最后,定义以冒号结尾。紧跟在def greet_user(): 后面的所有缩进行构成了函数体。
❷处的文本是被称为文档字符串 (docstring)的注释,描述了函数是做什么的。文档字符串用三引号括起,Python使用它们来生成有关程序中函数的文档。
代码行print(“Hello!”) (见❸)是函数体内的唯一一行代码,greet_user() 只做一项工作:打印Hello!

def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')

Hello, Jeese!
在函数greet_user() 的定义中,变量username 是一个形参 ——函数完成其工作所需的一项信息。在代码greet_user(‘jesse’) 中,值’jesse’ 是一个实参 。实参是调用函数时传递给函数的信息。
练习题8-1~8-2

def display_message():
    '''打印消息'''
    print("It is about the definition of function.")
    
display_message()
def favorite_book(title):
    print("One of my favorite books is "+title)
    
favorite_book('Alice in Wonderland')

函数调用中可能包含多个实参。向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可使用列表和字典。

8.2 传递实参

8.2.1 位置实参

调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。最简单的关联方式是基于实参的顺序。成为位置实参。

def describe_pet(animal_type, pet_name):
    """显示宠物信息"""
    print("\nI have a "+animal_type+".")
    print("My "+animal_type+"'s name is "+pet_name.title()+".")
    
describe_pet('hamster', 'harry')

I have a hamster.
My hamster’s name is Harry.

8.2.2 关键字实参

关键字实参时传递给函数的名称-值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆。关键字实参让你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。

def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')

调用函数时,明确只出了实参对应哪一个形参。关键字实参位置顺序无关紧要,但务必准确地指定函数定义中的形参名。

8.2.3 默认值

编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。因此,给形参指定默认值后,可在函数调用中省略相应的实参。使用默认值可简化函数调用,还可清楚地指出函数典型用法。
例如,你发现调用describe_pet()时,描述的大多都是小狗,就可将形参animal_tyoe的默认值设置为’dog’。

def describe_pet(pet_name,animal_type='dog'):
    """显示宠物信息"""
    print("\nI have a "+animal_type+".")
    print("My "+animal_type+"'s name is "+pet_name.title()+".")
    
describe_pet(pet_name='willie')

I have a dog.
My dog’s name is Willie.
注意,在这个函数的定义中,修改了形参的排列顺序。由于给animal_type 指定了默认值,无需通过实参来指定动物类型,因此在函数调用中只包含一个实参——宠物的名字。然而,Python依然将这个实参视为位置实参,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数定义中的第一个形参。这就是需要将pet_name 放在形参列表开头的原因所在。
使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让Python依然能够正确地解读位置实参。
现在使用这个函数的最简单方式是describe_pet('willie')

8.2.4 等效的函数调用

鉴于可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。请看下面的函数describe_pets() 的定义,其中给一个形参提供了默认值:def describe_pet(pet_name, animal_type='dog'):
基于这种定义,在任何情况下都必须给pet_name 提供实参;指定该实参时可以使用位置方式,也可以使用关键字方式。如果要描述的动物不是小狗,还必须在函数调用中给animal_type 提供实参;同样,指定该实参时可以使用位置方式,也可以使用关键字方式

# 一条名为Willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie')
# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

练习题8-3~8-5

def make_shirt(size,font):
    print("the T-shirt's size is "+size+" and its font is "+ font+"." )
    
make_shirt('L','Times New Roman')
def make_shirt(size='XXXL',font='I love Python'):
    print("the T-shirt's size is "+size+" and its font is "+ font+"." )
    
make_shirt()

8.3 返回值

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name=first_name+' '+last_name
    return full_name.title()

musician=get_formatted_name('jimi','hendrix')
print(musician)

8.3.2 让实参变成可选的

def get_formatted_name(first_name, last_name,middle_name=''):
    """返回整洁的姓名"""
    if middle_name:
        full_name=first_name+' '+middle_name+ ' '+last_name
    else:
        full_name=first_name+' '+last_name
    return full_name.title()

musician=get_formatted_name('jimi','hendrix')
print(musician)
musician=get_formatted_name('john','hooker','lee')
print(musician)

Jimi Hendrix
John Lee Hooker

8.3.2 返回字典

def build_person(first_name,last_name,age=''):
    """返回一个字典,其中包含有关一个人的信息"""
    person={'first': first_name,'last':last_name}
    if age:
        person['age']=age
    return person

musician=build_person('jimi','hendrix',age=27)
print(musician)

{‘first’: ‘jimi’, ‘last’: ‘hendrix’, ‘age’: 27}

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name=first_name+' ' +last_name
    return full_name.title()

#这是无限循环
while True:
    print("\nPlease tell me your name:")
    f_name=input("First name: ")
    l_name=input("Last name: ")
    
    formatted_name=get_formatted_name(f_name,l_name)
    print("\nHello, " + formatted_name + "!")
def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name=first_name+' ' +last_name
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(Enter 'q' at any time to quit)")
    f_name=input("First name: ")
    if f_name == 'q':
        break
    l_name=input("Last name: ")
    if l_name == 'q':
        break
    
    formatted_name=get_formatted_name(f_name,l_name)
    print("\nHello, " + formatted_name + "!")

练习题8-6~8-8

def city_country(city,country):
    print('"' + city.title() + ', ' + country.title() + '"')
    
city_country('Santiage', 'chile')
    
def make_album(singer,song,number=''):
    if number:
        album={'singer':singer,'song':song,'number':number}
    else:
        album={'singer':singer,'song':song}
    return album
print(make_album('a','b',15))
def make_album(singer,song,number=''):
    if number:
        album={'singer':singer,'song':song,'number':number}
    else:
        album={'singer':singer,'song':song}
    return album

while True:
    print("please input the singer and the song, you can quit anytime by input 'q'.")
    singer=input("The singer is: ")
    if singer == 'q':
        break
    song=input("The song is: ")
    if song == 'q':
        break
    print("\n")
    print(make_album(singer,song))

8.4 传递列表

def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg="Hello, " + name.title() + "!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

Hello, Hannah!
Hello, Ty!
Hello, Margot!

8.4.1 在函数中修改列表

unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models=[]

while unprinted_designs:
    current_design=unprinted_designs.pop()
    
    print("Printing model: " +current_design)
    completed_models.append(current_design)
    
print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design=unprinted_designs.pop()
    
        print("Printing model: " +current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
        
unprinted_designs=['iphone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

8.4.2 禁止函数修改列表

可用切片表示法[:]创建列表的副本。Print_models(unprinted_designs[:],completed_models)
这样函数print_models() 依然能够完成其工作,因为它获得了所有未打印的设计的名称,但它使用的是列表unprinted_designs 的副本,而不是列表unprinted_designs 本身.
练习题8-9~8-11

magicians=['zhao','qian','sun','li']
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
        
show_magicians(magicians)
magicians=['zhao','qian','sun','li']
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
        
show_magicians(magicians)
def make_great(magicians):
    great_magicians=[]
    for magician in magicians:
        great_magician='the Great' + magician
        great_magicians.append(great_magician)
    return great_magicians

great_magicians=make_great(magicians)
show_magicians(great_magicians)

8.5 传递任意数量的实参

def make_pizza(*toppings):
    print(toppings)
    
make_pizza('ppperoni')
make_pizza('mushrooms','green peppers','extra cheese')

(‘ppperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)
形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。函数体内的print 语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此

8.5.1 结合使用位置实参和任意数量实参

如果让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " +topping)
    
make_pizza(16,'ppperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

Making a 16-inch pizza with the following toppings:

  • ppperoni

Making a 12-inch pizza with the following toppings:

  • mushrooms
  • green peppers
  • extra cheese

8.5.2 使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。一个这样的示例是创建用户简介:你知道你将收到有关用户的信息,但不确定会是什么样的信息。在下面的示例中,函数build_profile() 接受名和姓,同时还接受任意数量的关键字实参:

def build_profile(first, last, **user_info):
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile

user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’, ‘field’: ‘physics’}
函数build_profile() 的定义要求提供名和姓,同时允许用户根据需要提供任意数量的名称—值对。形参**user_info 中的两个星号让Python创建一个名为user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。在这个函数中,可以像访问其他字典那样访问user_info 中的名称—值对。
练习题8-12~8-14

def sandwich(*toppings):
    for topping in toppings:
        print(topping + " added")
        
sandwich('pepper','onion')
def dic(builder,size,**info):
    profile={}
    profile['builder']=builder
    profile['size']=size
    for key,value in info.items():
        profile[key]=value
    return profile

dictionary=dic('zhang','da',changdu='henchang',daxiao='henda')
print(dictionary)

8.6 将函数存储在模块中

函数的优点之一时,使用它们将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解的多,还可更进一步,将函数存储在被成为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。

8.6.1 导入整个模块

要让函数是可导入的,需要先创建模块。模块时扩展名为.py的文件,包含要导入到程序中的代码。
pizza.py

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')

要调用被导入的模块中的函数,可指定导入的模块的名称pizza 和函数名make_pizza() ,并用句点分隔它们

8.6.2 导入特定的函数

from pizza import make_pizza
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

若使用这种语法,调用函数时就无需使用句点。由于我们在import 语句中显式地导入了函数make_pizza() ,因此调用它时只需指定其名称。

8.6.3 使用as给函数指定别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名——函数的另一个名称,类似于外号。要给函数指定这种特殊外号,需要这样做。
下面给函数make_pizza() 指定了别名mp() 。这是在import 语句中使用make_pizza as mp 实现的,关键字as 将函数重命名为你提供的别名

from pizza import make_pizza as mp

mp(16,'pepperoni')
mp(12, mushrooms','green peppers','extra cheese')

8.6.4 使用as给模块指定别名

通过模块指定简短的别名(如给模块pizza指定别名p)。

import pizza as p
p.make_pizza(6, 'pepperoni')

8.6.5 导入模块中的所有函数

使用星号(*)运算符可让Python导入模块中的所有函数

from pizza import *

import 语句中的星号让Python将模块pizza 中的每个函数都复制到这个程序文件中。由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。然而,使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。

import module_name
from module_name import function_name
from module_name import function_name as fn
import module_name as mn
from module_name import *
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值