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’)