《Python编程:从入门到实践》第八章:函数

函数

一、定义函数

使用关键字def来告诉Python你要定义一个函数。

def greet_user():
    print("Hello")

greet_user()

输出:

Hello
向函数传递信息

在函数定义def greet_user1()的括号内添加username。通过在这里添加username,就可让函数接受你给username指定的任何值。
调用greet_user1()时,可将一个名字传递给它。

def greet_user1(username):
    print("Hello " + username.title())

greet_user1('python')

输出:

Hello Python
实参和形参

在函数greet_user()的定义中,变量 username 是一个形参。
形参:函数完成其工作所需的一项信息。
在代码greet_user1( ’ python ’ )中,值 ’ python ’ 是一个实参。
实参:是调用函数时传递给函数的信息。
在greet_user(‘python’)中,将 实参 ’ python ’ 传递给了函数greet_user(),这个值被存储在 形参 username中。

二、传递实参
位置实参

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

例:一个描述宠物类型和名字的函数

def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name + ".\n")

describe_pet('hamster', 'harry')
describe_pet('harry', 'hamster')
#跟顺序有关

输出:

I have a hamster.
My hamster's name is harry.

I have a harry.
My harry's name is hamster.

  • 调用函数多次
def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name + ".\n")
    
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

输出:

I have a hamster.
My hamster's name is harry.

I have a dog.
My dog's name is willie.

关键字实参

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

def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name + ".\n")

describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'harry', animal_type = 'hamster')
#跟顺序无关

输出:

I have a hamster.
My hamster's name is harry.

I have a hamster.
My hamster's name is harry.

默认值

编写函数时,可给每个形参指定默认值。
在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。
因此,给形参指定默认值后,可在函数调用中省略相应的实参。使用默认值可简化函数调用,还可清楚地指出函数的典型用法。

def describe_pet1(pet_name, animal_type = 'dog'):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name + ".")

describe_pet1('willie')

输出:

I have a dog.
My dog's name is willie.

当显式地给animal_type提供一个实参时,Python将忽略这个形参的默认值。

def describe_pet1(pet_name, animal_type='dog'):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name + ".")

describe_pet1('harry', 'hamster')

输出:

I have a hamster.
My hamster's name is harry.

等效的函数调用

鉴于可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。请看下面的函数describe_pets()的定义,其中给一个形参提供了默认值:

def describe_pet(pet_name, animal_type='dog'):

下面对这个函数的所有调用都可行:

# 一条名为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')
避免实参错误

提供的实参多于或少于函数完成其工作所需的信息时,将出现实参不匹配错误。在Python中,应该确保函数调用和函数定义匹配。

三、返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。
函数返回的值被称为返回值
在函数中,可使用return语句将值返回到调用函数的代码行。
返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

返回简单值

例:输出人名

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)

输出:

Jimi Hendrix
让实参变成可选的

例:输出人名,适用于只有名和姓的人,也适用于有中间名的人:

def get_formatted_name1(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_name1('jimi', 'hendrix')
print(musician)
musician = get_formatted_name1('john', 'hooker', 'lee')
print(musician)

输出:

Jimi Hendrix
John Lee Hooker
返回字典

函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

例:函数接受姓名的组成部分,并返回一个表示人的字典:

def build_person(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person

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

输出:

{'first': 'jimi', 'last': 'hendrix'}

也可以修改为有年龄的:

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', 27)
print(musician)

输出:

{'first': 'jimi', 'last': 'hendrix', 'age': 27}
结合使用函数和while循环

例:结合使用函数get_formatted_name()和while循环,以更正规的方式问候用户。

def get_formatted_name2(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()

while True:
    print("Please tell me your name!")
    print("Enter 'quit' at any time to quit!")
    f_name = input("First name: ")
    if f_name == 'quit':
        print("Program quit")
        break
    l_name = input("Last name: ")
    if l_name == 'quit':
        print("Program quit")
        break
    formatted_name = get_formatted_name2(f_name, l_name)
    print("Hello " + formatted_name + "!\n")

输出:

Please tell me your name!
Enter 'quit' at any time to quit!
First name: jimi 
Last name: hendrix
Hello Jimi Hendrix!

Please tell me your name!
Enter 'quit' at any time to quit!
First name: quit
Program quit
四、传递列表

向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。
将列表传递给函数后,函数就能直接访问其内容。

def greet_users(names):
    for name in names:
        print("Hello " + name.title() + "!")
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

输出:

Hello Hannah!
Hello Ty!
Hello Margot!
在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。

例:有一个模拟打印机的程序,不使用函数

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:
        unprinted_design = unprinted_designs.pop()
        print("Printing model : " + unprinted_design)
        completed_models.append(unprinted_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)

输出:

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

The following models have been printed:
dodecahedron
robot pendant
iphone case
禁止函数修改列表

针对上一个例子,如果打印所有设计后,也要保留原来的未打印的设计列表。但由于将所有的设计都移出了unprinted_designs,这个列表变成了空的,原来的列表没有了。为解决这个问题,可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

function_name(list_name[:])

切片表示法[:]创建列表的副本。
如果不想清空未打印的设计列表,可以像下面这样调用print_models():

print_models(unprinted_designs[:], completed_models)

虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,因为让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。

五、传递任意数量的实参

有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。

例:预先不知道顾客会点几种配料时

def make_pizza(*toppings):
    print("Making a pizza with the following toppings:")
    for topping in toppings:
        print(topping)
    print("")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

输出:

Making a pizza with the following toppings:
pepperoni

Making a pizza with the following toppings:
mushrooms
green peppers
extra cheese

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

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

例:顾客选择尺寸和配料

def make_pizza1(size, *toppings):
    print("Making a " + size + "-inch pizza with the following toppings:")
    for topping in toppings:
        print(topping)
    print("")
make_pizza1('12', 'pepperoni')
make_pizza1('12', 'mushrooms', 'green peppers', 'extra cheese')

输出:

Making a 12-inch pizza with the following toppings:
pepperoni

Making a 12-inch pizza with the following toppings:
mushrooms
green peppers
extra cheese

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

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键-值对——调用语句提供了多少就接受多少。

例:创建用户简介:你知道你将收到有关用户的信息,但不确定会是什么样的信息。在下面的示例中,函数build_profile()接受名和姓,同时还接受任意数量的关键字实参:

def build_profile(first, last, **user_info):
    profile = {}
    profile['firstname'] = first
    profile['lastname'] = 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)

形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。

输出:

{'firstname': 'albert', 'lastname': 'einstein', 'location': 'princeton', 'field': 'physics'}
六、将函数存储在模块中

函数的优点之一是,使用它们可将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解得多。你还可以更进一步,将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。
通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点放在程序的高层逻辑上。这还能让你在众多不同的程序中重用函数。将函数存储在独立文件中后,可与其他程序员共享这些文件而不是整个程序。知道如何导入函数还能让你使用其他程序员编写的函数库。

导入整个模块

要让函数是可导入的,得先创建模块。
模块是扩展名为.py的文件,包含要导入到程序中的代码。
1、创建一个包含函数make_pizza()的模块。

pizza.py

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print(topping)

2、我们在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza()两次:

making_pizzas.py

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

Python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。你看不到复制的代码,因为这个程序运行时,Python在幕后复制这些代码。你只需知道,在making_pizzas.py中,可以使用pizza.py中定义的所有函数。
导入方法:只需编写一条import语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。如果你使用这种import语句导入了名为module_name.py的整个模块,就可使用下面的语法来使用其中任何一个函数:

module_name.function_name()
导入特定的函数

你还可以导入模块中的特定函数,这种导入方法的语法如下:

from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:

from module_name import function_0, function_1, function_2

对于前面的making_pizzas.py示例,如果只想导入要使用的函数,代码将类似于下面这样:

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

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

使用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')

指定别名的通用语法如下:

from module_name import function_name as fn
使用as给模块指定别名

你还可以给模块指定别名。通过给模块指定简短的别名(如给模块pizza指定别名p),让你能够更轻松地调用模块中的函数。

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

给模块指定别名的通用语法如下:

import module_name as mn
导入模块中的所有函数

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

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

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

最佳的做法是,要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值