函数
函数格式
def function(args):
doSomething
#调用函数
function(args1)
def———-标示符
function—–函数名称
args———允许传入的参数(形参,可以不传,也可以传多个)
doSomething–函数体
args1——–实际传入的参数(实参,和形参的格式保持一致)
注:1.传递参数时要按照函数的参数格式传递
2.函数调用中的每个实参都必须关联到函数定义中的一个形参,不可以不传或者漏传
3.注意传递参数的次序
4.形参可以指定默认值,调用时可以不传该参数
5.使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参
示例
#function
def describe_pet(pet_name, animal_type = 'cat'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
#合理调用
describe_pet('willie', 'dog')
#输出
#I have a dog.
#My dog's name is Willie.
#不合理调用(非错误调用,只是逻辑上不合理)
describe_pet('dog', 'willie')
#输出
#I have a willie.
#My willie's name is Dog.
#乱序调用
describe_pet(pet_name='willie', animal_type='dog')
#输出
#I have a dog.
#My dog's name is Willie.
#使用默认值
describe_pet(pet_name='willie')
#输出
#I have a cat.
#My cat's name is Willie.
返回值
在函数执行末尾(最后一步)使用“return”来返回运行结果
#示例
#functiion
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
函数中修改列表数据
制作3D打印模型。需要打印的设计存储在一个列表中,打印后移到另一个列表中
#function
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)
#输出
#Printing model: dodecahedron
#Printing model: robot pendant
#Printing model: iphone case
#
#The following models have been printed:
#dodecahedron
#robot pendant
#iphone case
注:禁止函数修改列表时,只要通过切片表示法[:] 创建列表的副本作为传递参数即可(print_models(unprinted_designs[:], completed_models))
传递任意数量参数
建立函数时,可以确定传入的参数建议指定形参,不确定的参数可以使用“*args”作为最后一个形参(*args作为元祖接受剩余的全部参数)
#示例-----制作指定尺寸和材料的披萨
#function
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, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#output
#Making a 16-inch pizza with the following toppings:
#- pepperoni
#
#Making a 12-inch pizza with the following toppings:
#- mushrooms
#- green peppers
#- extra cheese
也可以传递关键字参数,使用“**args”作为最后一个形参(传入的参数格式如下:key=value,key和value可以组合调用)
#functiion
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'}
函数与模块
模块—–python文件test.py即为test模块(model),模块中可以包含多个函数(示例中将上述方法均置于FunctionTest.py文件即FunctionTest模块中)
FunctionTest.py
#functiion1
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
#function2
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#function3
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()
调用示例(注意方法的引用格式)
注:因为使用的还是之前的例子,所以不再列出输出结果
导入模块(import model_name)
import FunctionTest
user_profile = FunctionTest.build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
导入指定的函数(from model_name import function_name)
from FunctionTest import build_profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
导入所有的函数(from model_name import *)
from FunctionTest import *
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
指定别名
1.给model指定别名
import FunctionTest as ft
user_profile = ft.build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
2.给函数指定别名(导入函数时使用,此时model不能指定别名)
from FunctionTest import build_profile as aaa
user_profile = aaa('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
函数编写注意事项
1.命名—–给函数指定描述性名称,且只在其中使用小写字母和下划线
2.注释—–每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式,信息可包含函数的名称、函数的功能、需要的实参、返回值得类型(注释可以选择性添加,建议养成良好的个人习惯)
3.形参—–给形参指定默认值时,等号两边不要有空格
4.实参—–使用关键字实参时,等号两边不要有空格
5.格式—–PEP 8(https://www.python.org/dev/peps/pep-0008/ )建议代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码。如果形参很多,导致函数定义的长度超过了79字符,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。
6.模块—–模块包含多个函数,使用两个空行将相邻的函数分开(确定相邻函数的首尾)
7.调用—–所有的import 语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序