目录
7.1 函数 input() 的工作原理
函数 input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python 将其赋给一个变量,以方便使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
函数 input() 接受一个函数——要向用户显示提示或说明。
7.1.1 编写清晰的工作原理
每当使用函数 input() 时,都应指定清晰易懂的提示。准确地指出希望用户提供什么样的信息。
name = input("please enter your name: ")
print(f"\nHello,{name}!")
即便提示超过一行,input() 语句也会非常清晰。
prompt = "If you tell us who you are, we can personalize the mesages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print(f"\nHello,{name}!")
运算符 += 在前面赋给变量 prompt 的字符串末尾附加一个字符串。
7.1.2 使用 int() 来获取数值输入
使用函数 input() 时,Python 将用户输入解读为字符串。
输入的是数 21 ,但输出的是字符串,如果将输入作为数来使用,就会发生错误。
为解救这个问题,可使用函数 int() 。让 Python 将输入视为数值。函数 int() 将数的字符串表示转换为数值表示:
用户根据提示输入 21 后,Python 将这个数解读为字符串,随后 int() 将这个字符串转换成了数值表示。这样就可以运行条件测试。
使用函数 int() 判断一个人是否满足坐过山车的身高要求:
height = input("How tall are you, in inches?")
height = int(height)
if height >= 48:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
7.1.3 求模运算符
处理数值信息时,求模运算符(%)是很有用的工具,它将两个数相除并返回余值。
求模运算符不会指出一个数是另一个数的几倍,只给出余数是多少。
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.") #偶数
else:
print(f"\nThe number {number} is odd") #奇数
7.2 while 循环简介
for 循环用于针对集合中的每个元素都执行一个代码块,而 while 循环则不断运行,直到指定的条件不满足为止。
7.2.1 使用 while 循环
可使用 while 循环来数数。例如,从 1 数到 5:
current_number = 1
while current_number <= 5:
print(current_number)
current_number +=1
7.2.2 让用户选择何时退出
可以使用 while 循环让程序在用户愿意时不断运行。在其中定义了一个退出值,只要用户输入的不是这个值,程序就将接着运行:
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)
print(message)
可以使用 if 语句,当输入 “quite” 时不会打印出来直接退出:
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 时让程序停止运行。
这样,在 while 语句中就只需要检查一个条件:标志的当前值是否为 True。
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)
在 while 循环中,在用户输入后使用一条 if 语句来检查变量 message 的值。如果用户输入的是 ‘quit’ ,就将变量 active 设置为 False。这将导致 while 循环不再执行。如果用户输入的不是 ‘quit’,就将输入作为一条消息打印出来。
7.2.4 使用 break 退出循环
要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break 语句。
使用 break 语句立即退出 while 循环:
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(f"I'd love to go to {city.title()}!")
以 while True 打头的循环将不断运行,直到遇到 break 语句。
注意:在任何 Python 循环中都可使用 break 语句。例如,可使用 break 语句来退出遍历列表或字典的 for 循环。
7.2.5 在循环中使用 continue
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句,不像 break 语句那样不再执行余下的代码并退出整个循环。例如,来看一个从 1 数到 10 但打印其中奇数的循环:
current_number = 0
while current_number < 10:
current_number += 1
if current_number %2 == 0:
continue
print(current_number)
7.2.6 避免无限循环
每个 while 循环都必须有停止运行的途径,这样才不会没完没了地执行下去。例如,循环从 1 数到 5:
x = 1
while x <= 5:
print(x)
x += 1
如果没有 x += 1 则循环将没完没了地运行:
x = 1
while x <= 5:
print(x)
7.3 使用 while 循环处理列表和字典
要记录大量的用户和信息,需要在 while 循环中使用列表和字典。
for 循环是一种遍历列表的有效方式,但不应在 for 循环中修改列表,否则将导致 Python 难以跟踪其中的元素。要遍历列表的同时对其进行修改,可使用 while 循环。通过将 while 循环同列表和字典结果起来使用,可收集、存储并组织大量输入,供以后查看和显示。
7.3.1 在列表之间移动元素
使用 while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再加入另一个已验证用户列表中。
# 首先创建一个带验证的用户列表
unconfirmed_users = ['alice','brian','candace']
# 和一个用于存储已验证用户的空列表
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经验证的用户都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
# pop() 以每次一个的方式从列表 unconfirmed_users 末尾删除未验证的用户
print(f"Verifying user:{current_user.title()}")
confirmed_users.append(current_user)
# append() 表示要添加到列表末尾的对象
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
①pop() 以每次一个的方式从列表 unconfirmed_users 末尾删除未验证的用户
②append() 表示要添加到列表末尾的对象
7.3.2 删除为特定值的所有列表元素
当列表中特定值只出现一次,使用函数 remove() 来删除列表中的特定值。如果特定值元素不止一个,需要运行一个 while 循环,直到列表中没有该值。
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 liake to let anouther person respond? (yes/no)")
if repeat == 'no':
polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name,response in responses.items():
print(f"{name} would like to climb {response}.")
只要 polling_active 为 True,Python 就运行 while 循环中的代码;用户输入 no ,标志 polling_active 将被设置为 False,而 while 循环将就此结束。