第8章 函数
greeter.py
def greet_user():
print("Hello!")
greet_user()
def greet_user(username):
print("Hello, " + username.title() + "!")
greet_user('jesse')
实参和形参
位置实参
pets.py
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')
describe_pet('dog', 'willie')
关键字实参
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')
describe_pet(pet_name='willie', animal_type='dog')
默认值
返回值
返回简单值
formatted_name.py
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)
def get_formatted_name(first_name, middle_name, last_name):
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'lee', 'hendrix')
print(musician)
让实参变成可选的,指定一个默认值(空字符串),并将其移到形参列表的末尾
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', 'lee', 'hendrix')
print(musician)
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
返回字典
person.py
def build_person(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
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)
结合使用函数和while循环
greeter.py
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 + "!")
传递列表
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
在函数中修改列表
不使用函数时
printing_models.py
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)
编写两个函数,重新组织代码
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)
禁止函数修改列表
如果不想清空未打印的设计列表,可以传递列表的副本
print_models(unprinted_designs[:], completed_models)
传递任意数量的实参
pizza.py
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
带*号的形参,创建一个空元组
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
实参封装到一个元组中,即便函数只收到一个值也如此
结合使用位置实参和任意数量实参
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')
使用任意数量的关键字实参
**形参,可以接受任意数量的键值对
user_profile.py
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)
**两个星号创建一个空字典,并将收到的键值对封装到这个字典中,使用时需要配合循环遍历字典中的键值对。
将函数存储在模块中
导入整个模块
import 模块名
调用被导入的模块中的函数:模块名称.函数名
导入特定的函数:from 模块名 import 函数名
用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:from 模块名 import 函数名1, 函数名2, 函数名3
使用这种方式调用函数时直接使用函数名,不需要再加模块名.
使用as给函数指定别名
使用as给模块指定别名
导入模块中的所有函数:from 模块名 import *(不推荐)
函数编写指南
应给函数指定描述性的名称,且只在其中使用小写字母和下划线
注释应紧跟在函数定义后面,并采用文档字符串格式
给形参指定默认傎时,=两边不要有空格
函数调用中的关键字实参,=两边也不要有空格
多个函数之间可使用两个空行将相邻的函数分开。
2023年9月27日