参考书籍:《Python编程 从入门到实践》
1. 函数定义
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
- 函数定义形式:
关键字def
+函数名
+:
- 三个引号表示文档字符串,描述了函数的用途
username
是形参,jesse
是实参
2. 传递参数
2.1 位置实参
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')
- 可多次调用函数
- 位置实参的顺序很重要
2.2 关键字实参
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')
需要准确指定函数定义中的形参名
2.3 默认值
def describe_pet( pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
- 形参指定默认值之后,后续实参若没有再重新指定值,则该处的实参就为开始指定的默认值。
- 函数调用的方式可以混用
- 给形参指定默认值时,等号两边不能有空格
3. 返回值
3.1 返回简单值
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)
return语句
将值返回到调用函数的代码行。- 调用返回值的函数时,需要提供一个变量,用于存储返回的值。
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()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
将可选的实参指定为一个默认的空字符串,即表示该实参是可由可无的
3.3 返回字典
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)
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("(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("\nHell, " + formatted_name + "!")
4. 传递列表
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移动到列表completed_moldes中
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.appene(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)
程序思路:每个函数都应负责一项具体的工作
5. 传递任意数量的实参
5.1 使用位置实参和任意数量实参
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, 'peperoni')
make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')
- 形参
*toppings
中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。- 结合位置实参使用时,任意数量实参需要放在最后
5.2 使用任意数量的关键字实参
def build_profiles(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)
- 形参
**user_info
中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有键-值对都封装到这个字典中。
6. 将函数存储在模块当中
6.1 创建模块
#创建名为pizza.py的模块
def make_pizza(size, *toppings):
"""概述要制作的披萨"""
print("\nMaking a " + str(size)+
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
模块,即扩展名为
.py
的文件,包含了要导入到程序中的代码。
6.2 导入整个模块
import pizza
pizza.make_pizza(16, 'peperoni')
pizza.make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')
import语句
会让Python打开文件pizza.py
,并将其中的所有函数都复制到这个程序中。- 调用模块中函数的格式:
模块名
+.
+函数名
6.3 导入特定的函数
from pizza import make_pizza, function1, ...
make_pizza(16, 'peperoni')
make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')
格式:
from
+模块名
+函数名
导入多个函数,用逗号隔开即可
6.4 指定别名
import pizza as p
from pizza import make_pizza as mp
p.make_pizza(16, 'peperoni')
mp(16, 'peperoni')
用
as
给模块和函数指定别名
网友评论