目录
7 用户输入和 while 循环
7.1 函数 input() 的工作原理
函数 input() 让程序暂停运行,等待用户输入一些文本。
7.1.1 编写清晰的程序
有时候,提示可能超过一行。可将提示存储在一个变量中,再将该变量传递给函数 input() 。
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
7.1.2 使用 int() 来获取数值输入
使用函数 input() 时,Python将用户输入解读为字符串。
age = input("How old are you? ")
>>>How old are you? 21
age
>>>'21'
可使用函数 int() ,它让Python将输入视为数值。函数 int() 将数字的字符串表示转换为数值表示,
age = input("How old are you? ")
>>>How old are you? 21
age = int(age)
age >= 18
>>>True
7.1.3 求模运算符
求模运算符( % )是一个很有用的工具,它将两个数相除并返回余数:
7.2 while 循环简介
for 循环用于针对集合中的每个元素都一个代码块,而 while 循环不断地运行,直到指定的条件不满足为止。
7.2.1 使用 while 循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
7.2.2 让用户选择何时退出
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
7.2.3 使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。
可让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
7.2.4 使用 break 退出循环
要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
注意 在任何Python循环中都可使用 break 语句。例如,可使用 break 语句来退出遍历列表或字典的 for 循环。
7.2.5 在循环中使用 continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句,它不像 break 语句那样不再执行余下的代码并退出整个循环。(即只退出当前该次循环)
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
如果当前的数字不能被2整除,就执行循环中余下的代码,将这个数字打印出来。(1,3,5,7,9)
7.2.6 避免无限循环
7.3 使用 while 循环来处理列表和字典
在 for 循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环。
7.3.1 在列表之间移动元素
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
# .pop()从列表删除末尾元素,或pop(i)
# .append(current_user)添加元素到列表
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
7.3.2 删除包含特定值的所有列表元素
# 结合while循环,remove(‘cat’)删除特定元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
7.3.3 使用用户输入来填充字典
可使用 while 循环提示用户输入任意数量的信息。将收集的数据存储在一个字典中,以便将回答同被调查者关联起来
responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
# 提示输入被调查者的名字和回答
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# 将答卷存储在字典中
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 greet_user():
"""显示简单的问候语""" #文档字符串
print("Hello!") #函数主体
greet_user()
关键字 def 来告诉Python你要定义一个函数。这是函数定义,向Python指出了函数名,还可能在括号内指出函数为完成其任务需要什么样的信息。
紧跟在 def greet_user(): 后面的所有缩进行构成了函数体。
文档字符串(docstring)的注释,描述了函数是做什么的。文档字符串用三引号括起
8.1.1 向函数传递信息
可在函数定义 def greet_user() 的括号内添加 username。通过在这里添加 元素,如username,就可让函数接受你给 username 指定的任何值。
def greet_user(username):
""" 显示简单的问候语 """
print("Hello, " + username.title() + "!")
greet_user('jesse')
8.1.2 实参和形参
在函数 greet_user() 的定义中,变量 username 是一个形参——函数完成其工作所需的一项信息。在代码 greet_user('jesse') 中,值 'jesse' 是一个实参。实参是调用函数时传递给函数的信息。我们调用函数时,将要让函数使用的信息放在括号内。
8.2 传递实参
函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。
向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可使用列表和字典。
8.2.1 位置实参
调用函数时,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') #位置实参
1. 调用函数多次
你可以根据需要调用函数任意次。
2. 位置实参的顺序很重要
使用位置实参来调用函数时,如果实参的顺序不正确,结果可能出乎意料。
8.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') #关键字实参
关键字实参的顺序无关紧要,因为Python知道各个值该存储到哪个形参中。下面两个函数调用是等效的:
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
8.2.3 默认值
编写函数时,可给每个形参指定默认值。
def describe_pet(pet_name, animal_type='dog'):
#给形参 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将把这个形参设置为 'dog'
8.2.4 等效的函数调用
可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。
def describe_pet(pet_name, animal_type='dog'): #给一个形参提供了默认值
下面对这个函数的所有调用都可行:与8.2.3中的输出结果相同
# 一条名为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')
8.2.5 避免实参错误
提供的实参多于或少于函数完成其工作所需的信息时,将出现 实参不匹配错误。
8.3 返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。
8.3.2 让实参变成可选的
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('john', 'lee', 'hooker')
print(musician)
调用这个函数时只提供了名和姓,它将不能正确地运行。为让中间名变成可选的,可给实参 middle_name 指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个实参。可给实参 middle_name 指定一个默认值——空字符串。程序改为如下:
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else: #在不使用middlename时,使其可选
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)
8.3.3 返回字典
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
新增一个可选形参 age ,并将其默认值设置为空字符串。
print("-----------------new test(002):-------------------")
print("------------- 传递函数参数 ----------------")
def rebuils_person(first_name,last_name,age = ''):
"""返回一个字典,包含名字信息"""
person = {'first':first_name, 'last':last_name}
if age:
person['age'] = age
return person
musician = rebuils_person('Yang','S',age = 24)
print(musician)
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("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':#每次提示用户输入时
break #使用 break 语句提供了退出循环
l_name = input("Last name: ")
if f_name == 'q':#每次提示用户输入
break #使用 break 语句提供了退出循环
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
8.4 传递列表
将列表传递给函数后,函数就能直接访问其内容。
8.4.1 在函数中修改列表
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
# 只要列表 unprinted_designs 中还有设计,while 循环就模拟打印设计的过程
while unprinted_designs:
#从该列表末尾删除一个设计,将其存储到变量 current_design中
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: " + current_design)
#再将该设计加入到列表 completed_models 中
completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
print(completed_models)
for completed_model in completed_models:
print(completed_model)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------->
可将上述代码编写为两个函数,效率更高。第一个函数将负责处理打印设计的工作,而第二个将概述打印了哪些设计。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------->
#第一个函数将负责处理打印设计的工作
#包含两个形参:一个需要打印的设计列表和一个打印好的模型列表。
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)
8.4.2 禁止函数修改列表
若想即便打印所有设计后,也要保留原来的未打印的设计列表。
可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。
将列表的副本传递给函数
function_name ( list_name [:])
切片表示法 [:] 创建列表的副本。在 print_models.py 中,如果不想清空未打印的设计列表,可像下面这样调用 print_models() :
print_models(unprinted_designs[:], completed_models)
8.5 传递任意数量的实参
Python允许函数从调用语句中收集任意数量的实参。
下面的函数只有一个形参 *toppings ,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中。
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')
形参名 *toppings 中的星号让Python创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。
8.5.1 结合使用位置实参和任意数量实参
Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
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')
8.5.2 使用任意数量的关键字实参
函数 build_profile() 接受名和姓,同时还接受任意数量的关键字实参
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)
函数 build_profile() 的定义要求提供名和姓,同时允许用户根据需要提供任意数量的名称 —值对。形参 **user_info 中的两个星号让Python创建一个名为 user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。
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)
8.6 将函数存储在模块中
函数的优点之一是,使用它们可将代码块与主程序分离。可将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。 import 语句允许在当前运行的程序文件中使用模块中的代码。
8.6.1 导入整个模块
让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码。
在pizza.py中
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
在making_pizzas.py
import pizza # 导入pizza.py
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
如果你使用这种 import 语句导入了名为 module_name.py 的整个模块,就可使用下面的语法来使用其中任何一个函数:
module_name.function_name()
8.6.2 导入特定的函数
from module_name import function_name #从模块中导入特定的函数
from module_name import function_0, function_1, function_2
#通过逗号分隔函数名,可根据需要从模块中导入任意数量的函数:
如,
from pizza import make_pizza
make_pizza(16, 'pepperoni')
#这种语法,调用函数时无需使用句点pizza.make_pizza()
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.3 使用 as 给函数指定别名
可给函数指定简短而独一无二的别名——函数的另一个名称,类似于外号。
如8.6.3的例子,可改为
from pizza import make_pizza as mp #使用as给函数make_pizza指定别名mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.4 使用 as 给模块指定别名
如8.6.1的例子,可改为
import pizza as p #使用as给模块pizza指定别名p
p.make_pizza(16, 'pepperoni') #导入的模块,所以使用p.make_pizza()
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.5 导入模块中的所有函数
使用星号( * )运算符可让Python导入模块中的所有函数:
from module_name import * #最好不要采用这种导入方法,易发生同名函数覆盖
8.7 函数编写指南
给形参指定默认值时,等号两边不要有空格:
def function_name( parameter_0, parameter_1 ='default value')
对于函数调用中的关键字实参,等号两边不要有空格:
function_name( value_0, parameter_1 ='value')
如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开。
所有的 import 语句都应放在文件开头。