Python编程:从入门到实践(读书笔记:第8章 函数)

本文是《Python编程:从入门到实践》一书的第8章读书笔记,详细介绍了Python函数的使用,包括定义函数、传递参数、默认值、返回值、可选形参、传递任意数量的实参以及如何导入和使用模块。通过实例展示了如何编写和调用函数,以及编写函数的规范和最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

coding=gbk

coding:utf-8!

定义函数

def great_user():
“”“显示简单的问候语”""
print(“Hello!”)
great_user()

向函数传递信息

print()
def great_user(username):
“”“显示简单的问候语”""
print("Hello, " + username.title() + “!”)
great_user(‘jessie’)

实参合形参

传递实参

位置实参

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

调用函数多次

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

关键字实参

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

默认值

def describe_pet(pet_name, animal_type=‘dog’): # 注意这里修改了形参顺序
“”“显示宠物信息4"”"
print("\nI have a " + animal_type + “.”)
print("My " + animal_type + "'s name is " + pet_name.title() + “.”)
describe_pet(pet_name = ‘willie’) # 也可直接用describe_pet(‘willie’)

如果要描述的不是小狗,可显式地给animal_type提供实参,让Python忽略形参默认值

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

返回值 使用return语句

返回简单值

print()
def get_formatted_name(first_name, last_name):
“”“返回整洁的姓名1"”"
full_name = first_name + ’ ’ + last_name
return full_name.title()

调用返回值的函数时,需要提供一个变量,用于存储返回的值(如musician)

musician = get_formatted_name(‘jimi’, ‘hendrix’)
print(musician)

返回函数适用于需要分别存储大量名和姓的大型程序中

让实参编程可选的

print()
def get_formatted_name(first_name, middle_name, last_name):
“”“返回整洁的姓名2"”"
full_name = first_name + ’ ’ + middle_name + ’ ’ + last_name
return full_name.title()
musician = get_formatted_name(‘john’, ‘lee’, ‘hooker’)
print(musician)

并非所有人都有中间名,将中间名编程可选的

给middle_name指定一个默认值——空字串符(不需要留空格)

def get_formatted_name(first_name, last_name, middle_name = ‘’):
“”“返回整洁的姓名2"”"
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)

返回字典

print()
def build_person(first_name, last_name):
“”“返回一个字典,其中包含有关一个人的信息1"”"
person = {‘first’: first_name, ‘last’: last_name} # 注意这里值不加单引号
return person
musician = build_person(‘jimi’, ‘hendrix’)
print(musician)

新增可选形参age

def build_person(first_name, last_name, age=’’):
“”“返回一个字典,其中包含有关一个人的信息2"”"
person = {‘first’: first_name, ‘last’: last_name}
if age:
person[‘age’] = age
return person
musician = build_person(‘jimi’, ‘hendrix’, age=27)
print(musician)

结合使用函数和while循环

print()
def get_formatted_name(first_name, last_name):
“”“返回整洁的姓名3"”"
full_name = first_name + ’ ’ + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter ‘quit’ at any time to quit)")
f_name = input(“First name:”)
if f_name == ‘quit’:
break
l_name = input(“Last name:”)
if l_name == ‘quit’:
break
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + “!”)

传递列表

print()
def great_users(names):
“”“向列表中的每位用户都发出简单的问候”""
for name in names:
msg = "Hello, " +name.title() + “!”
print(msg)
usernames = [‘hannah’, ‘ty’, ‘margot’]
great_users(usernames)

在函数中修改列表

print()
#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = [‘iphone case’, ‘robot pendant’, ‘dodecahedron’]
completed_models = []

模拟打印每个设计,直到没有未打印的设计为止

打印每个设计后,都将其移到列表completed_models中

while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
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)

重新组织上面代码,编写2个函数,使得程序的功能更易看清

print()
def print_models(unprinted_designs, completed_models):
“”"
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
“”"
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
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)

禁止函数修改列表

切片表示法[:]

用print_models(unprinted_designs[:], completed_models)来代替

除非有充分理由需要传递副本,否则避免花时间和内存创建副本,提高效率

传递任意数量的实参

print("\n传递任意数量的实参")
def make_pizza(toppings): # 星号作用:创建名toppings的空元组
“”“打印顾客点的所有配料”"" # 并将收到的所有值都封装到这个元祖中
print(toppings) # 元祖与列表类似,区别在于元组元素不能修改
make_pizza(‘pepperoni’)
make_pizza(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

将上面语句换成循环,对配料表进行遍历

print("\n对配料表进行遍历")
def make_pizza(*toppings):
“”“概述要制作的比萨”""
print(“Making a pizza with the following toppings:”)
for topping in toppings:
print("- " + topping)
make_pizza(‘pepperoni’)
make_pizza(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

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

先匹配位置实参和关键字实参,将接纳任意数量实参的形参放在最后

print("\n结合使用位置实参合任意数量实参")
def make_pizza(size, *toppings):
“”“概述要制作的比萨”""
print(“Making a " + str(size) +
“-inch pizza with the following toppings:”)
for topping in toppings:
print(”- " + topping)
make_pizza(16, ‘pepperoni’)
make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

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

print("\n使用任意数量的关键字实参")
def build_profile(first, last, **user_info): # 2个*建立空字典
“”“创建一个字典,其中包含我们知道的有关用户的一切”""
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)

将函数存储在模块中,再用import语句允许当前运行的程序使用模块中代码

县创建模块,再导入整个模块(模块扩展名也是.py的文件)

模块pizza.py示例

print("\n模块pizza.py例子")
import pizza
pizza.make_pizza(16, ‘pepperoni’)
pizza.make_pizza(12, ‘mushrooms’, ‘green peppers’,
‘extra cheese’)

模块和程序需要在同一个目录中

import pizza让Python打开文件pizza.py,并将其中函数复制到这个程序中

调用被导入的模块中的函数:

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

导入特定的函数,甚至是特定任意数量的函数,语法如下:

“from module_name import function_0, function_1, function_2”

如果是任意数量函数,需要用逗号分隔函数名

上面同一个例子导入方法如下:

print("\n同一个例子用导入特定函数语法:")
from pizza import make_pizza
make_pizza(16, ‘pepperoni’)
make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

为避免混淆,可使用as给导入的函数指定别名,需要在导入函数时使用

上面同一个例子

print("\n同一个例子用as给函数指定别名:")
from pizza import make_pizza as mp
mp(16, ‘pepperoni’)
mp(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

用as给模块指定别名

语法:import module_name as m

print("\n用as给模块指定别名:")
import pizza as p
p.make_pizza(16,‘pepperoni’)
p.make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

好像给模块指定别名 vs 给模块中函数指定别名 没法同时进行

导入模块的所有函数,用*代替所有函数

语法:from module_name import *

print("\n导入模块的所有函数:")
from pizza import *
make_pizza(16, ‘pepperoni’)
make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

由于导入了每个函数,可通过函数名称来调用函数,不需要句点表示法

非自己编写的大型模块,最好不要采用这种导入方法

要么只导入需要使用的函数,要么导入整个模块并使用句点表示法

函数编写指南

给函数指定描述性名称,且只是用小写字母和下划线(模块命名一样)

函数应包含简要阐述其功能的注释,注释紧跟在函数定义后面

采用文档字串符格式

给形参指定默认值时,等号两边不要有空格!

eg. def function_name(parameter_0, parameter_1=‘default value’)

对于函数调用中的关键字实参,也应遵循这约定:

eg. function_name(value_0, parameter_1=‘value’)

https://www.python.org/dev/peps/pep-0008/

代码行长度不要超过79字符

如果函数形参很多,可在函数定义中输入左括号后按会车键

并在下一行按2次tab键,从而将形参列表和只缩进一层的函数体区分

如果程序或模块有多个函数,可使用2个空行将相邻的函数分开

所有的import语句都应放在文件开头!

唯一例外情况:在文件开头使用了注释来描述整个程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值