for 循环针对于集合中的每个元素的一个代码块 而 while 循环不断的运行 直到指定的条件不满足
current_number 1 while current_number 5: print(current_number) current_number 1
promot nTell me something, and I will repeat it back to you: promot nEnter quit to end the program. message while message ! quit : message input(promot) if message ! quit : print(message)
使用标志
导致程序结束的事件有很多时 使用 while 很难检测
在要求很多条件都满足才继续运行的程序中 可定义一个变量 用于判断整个程序是否处于活动状态 这个变量称为标志
可以让程序在标志为 True 时继续运行 并在任何事件导致标志的值为 False 时让程序停止运行
在 while 中只需要检查标志的当前值是否为 True 并将所有测试放在其他地方
promot nTell me something, and I will repeat it back to you: promot nEnter quit to end the program. active True while active: message input(promot) if message quit : active False else: print(message)
使用 break 退出循环
要立即退出 while 循环 不再运行循环中余下的代码 也不管条件测试的结果如何 使用 break 语句
break 语句用于控制程序流程 在任何Python循环中都可以使用 break 语句
以 while True 打头的循环将不断运行 知道遇到 break 语句位置
promot nPlease enter your name of city you have visited: promot n(Enter quit when you are finished.) while True: city input(promot) if city quit : break else: print( I d love to go to city.title() . )
在循环中使用 continue
要返回循环开头 并根据条件测试结果决定是否继续执行循环 continue 语句不像 break 语句那样不再执行行余下的代码并退出整个循环
current_number 0 while current_number 10: current_number 1 if current_number % 2 0: continue print(current_number)
避免无限循环
每个 while 循环都必须有停止运行的途径 按Ctrl C
for 循环是一种遍历列表的有效方式 但是在 for 循环中不应该修改列表 否则将导致Python难以跟踪其中的元素
要在遍历列表的同时对其修改 可以使用 while 循环
在列表之间移动元素
un/confirm/ied_users [ alice , brian , candace ] /confirm/ied_users [] while un/confirm/ied_users: current_user un/confirm/ied_users.pop() print( Verifying user: current_user.title()) /confirm/ied_users.append(current_user) print( nThe following users have been /confirm/ied: ) for /confirm/ied_user in /confirm/ied_users: print(/confirm/ied_user.title())
删除包含特定值的所有列表元素
不断运行 while 循环 直到列表中所有该值全都被删除
pets [ dog , cta , dog , goldfish , cat , rabbit , cat ] print(pets) while cat in pets: pets.remove( cat ) print(pets)
使用用户输入来填充字典
使用 while 循环提示用户输入任意数量的信息
responses {}
polling_active True
while polling_active:
name input( nWhat is your name? )
response input( Which mountain would you like to climb somebody? )
responses[name] response
repeat input( Would you like to let another person respond?(yes/no) )
if repeat no :
polling_active False
print( n--- Poll Results --- )
for name, response in responses.items():
print(name would like to climb response . )
8 函数
函数时带名字的代码块 用于完成具体工作 要执行函数定义的特定任务可调用该函数
8.1 定义函数使用关键字 def 来告诉Python你要定义一个函数 这是函数定义 向Python指出了函数名 还可能在括号内指出函数为完成其任务需要什么样的信息
文档字符串的注释描述了函数是做什么的 文档字符串用三引号括起 Python使用他们来生成有关程序中函数的文档
要调用函数 可依次指定函数名以及用括号括起的必要信息
def greet_user(): 显示简单的问候语 print( Hello! ) greet_user()
向函数传递信息
def greet_user(username): 显示简单的问候语 print( Hello username.title() ! ) greet_user( jesse )
实参和形参
在函数 greet_user 中 变量username是一个形参——函数完成其工作所需额一项信息
在代码 greet_user(‘jesse’) 中 值 ‘jesse’ 是一个实参 实参是调用函数时传递给函数的信息
鉴于函数定义中可能包含多个形参 因此函数调用汇总也可能包含多个实参 向函数传递实参的方式很多 可使用位置实参 值要求是从哪的顺序与形参的顺序相同 也可以使用关键字实参 其中每个实参都有变量名和值组成 还可以使用列表和字典
位置实参
调用函数时 Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此最简单的关联方式就是基于实参的顺序 即位置实参
调用函数多次 可以根据需要调用函数任意次
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 )
默认值
编写函数时 可给每个形参指定默认值 在调用函数中给形参提供了实参时 Python将使用指定的实参值 否则将使用形参的默认值
使用默认值时 在形参列表中必须先列出没有默认值的形参 再列出有默认值的形参
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 )
在这个函数的定义中 修改了形参的排列吮吸 由于给 animal_type 指定了默认值 无需通过实参来指定动物类型 因此在函数调用中只包含一个实参——宠物的名字
然而Python依然将这个实参视为位置实参 因此如果函数调用中只包含宠物的名字 这个实参将关联到函数定义中的第一个形参 所以需要将 pet_name 放在形参列表开头
等效的函数调用
鉴于可混合使用位置实参、关键字实参和默认值 通常有很多等效的函数调用方式
def describe_pet(pet_name, animal_type dog ): #一条名为Willie的小狗 describe_pet( willie ) describe_pet(pet_name willie ) #一只名为Harry的仓鼠 describe_pet( harry , hamster ) describe_pet(pet_name harry , animal_type hamster ) describe_pet(animal_type hamster , pet_name harry )
避免实参错误
你提供的实参多于或少御函数完成其工作所需要的信息时 会出现实参不匹配的错误
函数并非总是直接显示输出 可以处理一些数据返回一个或一个组值
使用 return 语句将值返回到调用函数的代码行
调用返回值的函数时 需要提供一个变量 用于存储返回的值
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, 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)
给形参 middle_name 指定一个默认值——空字符串 并在用户没有提供中间名时不使用这个形参
返回字典
函数可以返回任何类型的值 包括列表和字典等较为复杂的数据结构
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 循环
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 formatter_name get_formatted_name(f_name, l_name) print( nHello, formatter_name.title() ! )8.4 传递列表
将列表传递给函数后 函数就能直接访问其内容
def greet_users(names): 向列表中的每位用户都发出简单的问候 for name in names: msg Hello, name.title() ! print(msg) usernames [ hannah , ty , margot ] greet_users(usernames)
在函数中修改列表
在函数中对这个列表所做的任何修改都是永久性的
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): 模拟打印每个设计 知道没有未打印的设计位置 打印每个设计后 都将其移动到列表completed_model中 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)
禁止函数修改列表
可向函数传递列表的副本而不是原件 但除非有充分的理由须有传递副本 否则还是应该将原始列表传递给函数
切片表示法 [:] 创建列表的副本
funcation_name(list_name[:])8.5 传递任意数量的实参
预先不知道函数需要接受多少个实参 Python允许函数从调用语句中收集任意数量的实参
形参名 *toppings 中的星号让Python创建一个名为 toppings 的控元组 并将收集到的所有值都封装到这个元组中
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 )
使用任意数量的关键字实参
有时候 需要接受任意数量的实参 但预先不知道传递给函数的会是什么样的信息 可将函数编写成能够接受任意数量的键-值对——调用语句提供了多少就接受多少
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)
形参 **user_info 中的两个星号让Python创建一个名为 user_info 的空字典 并将收到的所有名称-值对都封装到这个字典 在这个字典中可以像访问其他字典一样访问 user_info 中的名称-值对
8.6 将函数存储在模块中函数的优点之一 使用他们可以将代码块与主程序分离 通过给函数指定描述性名称 可让主程序容易理解的多
还可以更进一步 将函数存储在被称为模块的独立文件中 再将模块导入到主程序中
import 语句允许在当前运行的程序文件中使用模块中的代码
通过将函数存储到独立的文件中 可隐藏程序中代码的细节 将重点放在程序的高层逻辑上 还能在众多不同的程序中重用函数
firsr.py
def make_pizza(size, *toppings): 概述要制作的披萨 print( nMaking a str(size) -inch pizza with the following toppings: ) for topping in toppings: print( - topping)
second.py
import first first.make_pizza(16, pepperoni ) first.make_pizza(12, mushrooms , green peppers , extra cheese )
module_name.function_name()
导入特定函数
from module_name import function_name from module_name import function_0, function_1, function_2
second.py
from first import make_pizza make_pizza(16, pepperoni ) make_pizza(12, mushrooms , green peppers , extra cheese )
使用 as 给函数指定别名
from module_name iport function_name as fn
second.py
from first import make_pizza as f f(16, pepperoni ) f(12, mushrooms , green peppers , extra cheese )
使用 as 给模块指定别名
import module_name as mn
second.py
import first as f f.make_pizza(16, pepperoni ) f.make_pizza(12, mushrooms , green peppers , extra cheese )
导入模块中所有的函数
使用星号 * 运算符可让Python导入模块中的所有函数 使用非自己编写的大型模块时 不要采用这个导入方法
from module_name import *
second.py
from first import * make_pizza(16, pepperoni ) make_pizza(12, mushrooms , green peppers , extra cheese )8.7 函数编写指南
每个函数都应包含简要地阐述其功能的注释 该注释跟在函数定义的后面
给形参设定默认值的时候 等号两边不要有空格
程序模块包括多个函数 使用两个空行将相邻的函数分隔开



