8.1定义函数
def greet_user():
'''显示简单的问候语'''
print("Hello!")
greet_user()
Hello!
8.1.1 向函数传递消息
def greet_user(username):
'''显示简单的问候语'''
print("Hello,"+username.title()+'!')
greet_user("Zhanghaokun")
Hello,Zhanghaokun!
8.1.2 形参和实参
上面案例中username为形参 "Zhanghaokun"实参
8.2传递实参
8.2.1 位置实参
def describe_pet(animal_type,pet_name):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("\nMy "+animal_type+"'s name is: "+pet_name)
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("\nMy "+animal_type+"'s name is: "+pet_name)
describe_pet(animal_type="dog",pet_name="hotspurs")
I have a dog.
My dog’s name is: hotspurs
8.2.3 默认值
## 形参列表中,有默认值的必须放后面
def describe_pet(pet_name,animal_type="dog"):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("\nMy "+animal_type+"'s name is: "+pet_name)
describe_pet("hotspurs")
I have a dog.
My dog’s name is: hotspurs
8.3返回值
def get_formatted_name(first_name,last_name):
"""返回整洁的名字"""
full_name = first_name + " " + last_name
return full_name.title()
my_name = get_formatted_name("zhang","haokun")
print(my_name)
Zhang Haokun
8.3.1返回简单值
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()
my_name = get_formatted_name("zhang","hao","kun")
print(my_name)
Zhang Kun Hao
8.3.3返回字典
def build_person(first_name,last_name):
"""返回一个字典,包含一个人的信息"""
person = {
'first' : first_name,
'last' : last_name
}
return person
me = build_person("zhang","haokun")
print(me)
{‘first’: ‘zhang’, ‘last’: ‘haokun’}
8.3.4结合使用函数和while循环
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("\nenter 'q' at any time to quit")
f_name = input("First: ")
if f_name == 'q':
break
l_name = input("Lat: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name,l_name)
print("\nHello, "+formatted_name.title())
Please tell me your name
enter ‘q’ at any time to quit
Hello, Zhang Haokun
Please tell me your name
enter ‘q’ at any time to quit
8.4传递列表
def greet_users(names):
"""向列表中的每位用户发出简单的问候信息"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
user_names = ["tom","tony","jerry","lisa"]
greet_users(user_names)
Hello, Tom!
Hello, Tony!
Hello, Jerry!
Hello, Lisa!
8.4.1在函数中修改列表
# 为用户提交的设计制作3D打印模型的公司,需要打印的设计存储在一个列表中,打印后移到另一个列表中
# 不使用函数
# 先创建一个列表,其中包含一些要打印的设计
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)
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,complete_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
8.4.2禁止函数修改列表
向函数传递列表的副本
function_name(list_name[:])
8.5传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客点的所有配料
*toppings ---> 封装成一个列表
"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
(‘pepperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)
def make_pizza(*toppings):
"""打印顾客点的所有配料
*toppings ---> 封装成一个列表
"""
print("\nMake a pizza with the following toppings:")
for topping in toppings:
print('-' + topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
Make a pizza with the following toppings:
-pepperoni
Make a pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
8.5.1结合位置实参和任意数量参数
# 位置:位置实参 关键字参数 其他
def make_pizza(size,*toppings):
"""打印顾客点的所有配料
*toppings ---> 封装成一个列表
"""
print("\nMake a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print('-' + topping)
make_pizza(12,'pepperoni')
make_pizza(16,'mushrooms','green peppers','extra cheese')
Make a 12-inch pizza with the following toppings:
-pepperoni
Make a 16-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
8.5.2使用任意数量的关键字参数
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的用户"""
"""
**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("zhang","haokun",location="xi'an",field="CS")
print(user_profile)
{‘first_name’: ‘zhang’, ‘last_name’: ‘haokun’, ‘location’: “xi’an”, ‘field’: ‘CS’}
8.6将函数存储在模块中
8.6.1导入整个模块
使用import
8.6.2导入特定的函数
from … import …
8.6.3使用as给函数起别名
from … import … as …
8.6.4导入模块中所有函数
from … import *