前言
学习至此,我感觉速度放慢,练习题目和找报错逐渐有了难度。并且,我会发现自己无法及时调动以前学习的知识。不过这很正常,在这个阶段我需要做的是:1. 允许自己把速度放慢,速度远不如质量重要。弄清楚每一处的逻辑和构架,并且时时回看。2.忘记是常见的,因为不熟练,因为练习的少。只要在需要的时候一遍遍反复查看,就有记住的时候。加油~
第7章用户输入和while循环
在本章中,你将学习如何接受用户输入,让程序能够对其进行处理。在程序需要一个名字时,你需要提示用户输入该名字;程序需要一个名单时,你需要提示用户输入一系列名字。为此,你需要使用函数input()。
你还将学习如何让程序不断地运行,让用户能够根据需要输入信息,并在程序中使用这些信息。为此,你需要使用while循环让程序不断地运行,直到指定的条件不满足为止。通过获取用户输入并学会控制程序的运行时间,可编写出交互式程序。
1. 函数input()的工作原理
message=input('Tell me something and I will repeat it back to you:')
print(message)
Tell me something and I will repeat it back to you:Hello world!
Hello world!
在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you:。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户。
【编写清晰的程序】
prompt = "If you tell us who you are, we can send you a message."
prompt += "What is your name?:"
name=input(prompt)
print(f'Hello {name}.')
第1行将消息的前半部分存储在变量prompt中;在第2行中,运算符+=在存储在prompt中的字符串末尾附加一个字符串。
【使用int()来获取数值输入】
age = input('How old are you?:')
age=int(age)
if age>=18:
print(age)
else:
print('You are under 18 now.')
函数int()将数字的字符串表示转换为数值表示
【求模运算符%】
它将两个数相除并返回余数。求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少。如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。你可利用这一点来判断一个数是奇数还是偶数。
number=input('Please input a number, and I will tell you if it is even or odd:')
number=int(number)
if number%2==0:
print(f'{number} is even.')
else:
print(f'{number} is odd.')
【在Python 2.7中获取输入 raw_input()】
【练习】
7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。
car=input('Which type of cars do you want to borrow:')
print(f'Let me see if I can find you a {car}.')
7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。
people=input('How many people are dining tonight?:')
people=int(people)
if people > 8:
print(f'There are no empty tables here.')
else:
print(f'There are enough tables.')
7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是10的整数倍。
number=input('Please input a number:')
number=int(number):
if number %10==0 :
print(f'{number} is an integer multiple of ten.')
else:
print(f'{number} is not an integer multiple of ten.')
2.while循环简介
for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
current_number =1
while current_number<=5:
print(current_number)
current_number+=1
在第1行,我们将current_number设置为1,从而指定从1开始数。接下来的while循环被设置成这样:只要current_number小于或等于5,就接着运行这个循环。循环中的代码打印current_number的值,再使用代码current_number+= 1(代码current_number = current_number+1的简写)将其值加1
【让用户选择何时退出】
prompt='Tell me something,and I will repeat it back to you:'
prompt+="\nOr enter 'Quit' to end the program."
message=""
while message.lower() != 'quit':
message=input(prompt)
print(message)
我们定义了一条提示消息,告诉用户他有两个选择:要么输入一条消息,要么输入退出值(这里为'quit')。接下来,我们创建了一个变量——message(见❷),用于存储用户输入的值。我们将变量message的初始值设置为空字符串"",让Python首次执行while代码行时有可供检查的东西。Python首次执行while语句时,需要将message的值与'quit'进行比较,但此时用户还没有输入。如果没有可供比较的东西,Python将无法继续运行程序。为解决这个问题,我们必须给变量message指定一个初始值。虽然这个初始值只是一个空字符串,但符合要求,让Python能够执行while循环所需的比较。只要message的值不是'quit',这个循环(见❸)就会不断运行。等到用户终于输入'quit'后,Python停止执行while循环,而整个程序也到此结束。
prompt='Tell me something,and I will repeat it back to you:'
prompt+="\nOr enter 'Quit' to end the program."
message=""
while message.lower() != 'quit':
message=input(prompt)
if message.lower()!='quit':#防止打印quit
print(message)
【使用标志】
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。你可让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需检查一个条件——标志的当前值是否为True,并将所有测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序变得更为整洁。
prompt='Tell me something,and I will repeat it back to you:'
prompt+="\nOr enter 'Quit' to end the program."
message=""
active=True #我们将变量active设置成了True,让程序最初处于活动状态,只要是active就一直执行。
while active: #在while循环中,if语句检查变量message的值。
message=input(prompt)
if message.lower() =='quit':#如果用户输入'quit',active变成False,while循环不再继续执行。
active=False
else:
print(message)
【使用break退出循环】
prompt='Tell me something,and I will repeat it back to you:'
prompt+="\nOr enter 'Quit' to end the program."
message=""
while True: #在while循环中,if语句检查变量message的值。
message=input(prompt)
if message.lower() =='quit':#如果用户输入'quit',active变成False,while循环不再继续执行。
break
else:
print(message)
以while True打头的循环将不断运行,直到遇到break语句。
【在循环中使用continue】
current_number=0
while current_number<=10:
current_number+=1
if current_number%2==0:
continue
else:
print(current_number)
1 3 5 7 9 11
【避免无限循环】
如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。
要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。如果你希望程序在用户输入特定值时结束,可运行程序并输入这样的值;如果在这种情况下程序没有结束,请检查程序处理这个值的方式,确认程序至少有一个这样的地方能让循环条件为False或让break语句得以执行。
【练习】
7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
ingredients=input('Please input your ingredients:')
while ingredients.lower() !='quit':
print(f'We will add this {ingredients}.')
ingredients=input("\n Please add another ingredients,or enter 'Quit' to end this program.")
print('Program ended.')
进阶版: 假如第一次加m,第二次加b,当前输出结果是分开的,第一次加m,第二次加b。如何让输出结果也累加。
创建一个result=””
ingredients = input('Please input your ingredients:')
result = ""
while ingredients.lower() != 'quit':
result += ingredients + " "
# Remove trailing whitespace and split the ingredients
ingredient_list = result.strip().split()
# Join the ingredients with 'and' and print the final result
final_result = ' and '.join(ingredient_list)
print(f'We will add these ingredients: {final_result}')
ingredients = input("\n Please add another ingredient, or enter 'quit' to end this program: ")
print('Program ended.')
7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
原始错误代码:
age = input("Print your age(Enter'quit'to end the program):")
active=True
while active:
age = int(age) #此时再将age转换成整数
if age<3:
print("You will be free.")
elif age<12:
print("It's 10$ per ticket.")
else:
print("It's 15$ per ticket.")
if age =='quit':
active= false
break
为什么age = input("Print your age(Enter'quit'to end the program):")在active=True前面就一直循环??初次报错,在我输入14后,代码一直在循环。
错误方法:没修改 age。
循环的原因:需要反复判断输入,所以每次循环都要输入age,input需要在循环里面。
正确:
active=True
while active:
age = input("Print your age(Enter'quit'to end the program):")
#代码首先检查输入是否为'quit',然后再尝试将其转换为整数。如果输入是'quit',则输出一条消息并退出循环。
# 如果输入是有效的年龄,它将继续执行后续的逻辑。
if age =='quit':
active= false
break
age = int(age) #此时再将age转换成整数
if age<3:
print("You will be free.")
elif age<12:
print("It's 10$ per ticket.")
else:
print("It's 15$ per ticket.")
7-6 三个出口:以另一种方式完成练习7-4或练习7-5,在程序中采取如下所有做法。·在while循环中使用条件测试来结束循环。·使用变量active来控制循环结束的时机。·使用break语句在用户输入'quit'时退出循环。
7-7 无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl+C,也可关闭显示输出的窗口)。
3.使用while循环来处理列表和字典
while循环修改列表和字典
【在列表之间移动元素-验证用户】
unconfirmed_users=['feifei','ashley','tony']
confirmed_users=[]
while unconfirmed_users:#一直循环直到unconfirmed_users中没有人。
current_users = unconfirmed_users.pop() #从列表最后一个开始删除,储存到变量current_users中。
print(f'Verifying users:{current_users}.')
confirmed_users.append(current_users) #再加入到confirmed_users中。这是一个循环。
print('The following users have been confirmed: ')
for confirmed_user in confirmed_users: #新的循环
print(confirmed_user.title())
【删除包含特定值的所有列表元素】 while+remove
删除列表中所有包含特定值的元素
users=['feifei','hym','tony','tony','ashley','tony']
print(users)
while 'tony' in users:
users.remove('tony')
print(users) #循环结束后,只打印一次。
Python进入while循环,因为它发现'tony'在列表中至少出现了一次。进入这个循环后,Python删除第一个'tony'并返回到while代码行,然后发现'tony'还包含在列表中,因此再次进入循环。它不断删除'tony',直到这个值不再包含在列表中,然后退出循环并再次打印列表。
【使用用户输入来填充字典】
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 #Stores the user's response in the responses dictionary using their name as the key.
# 看看是否还有人要参与调查
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(f'{name} would like to climb {response}.")
【练习】
7-8 熟食店:创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches的空列表。遍历列表sandwich_orders,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders=['tuna sandwiches','egg sandwiches','baconic sandwiches']
finished_sandwiches= []
while sandwich_orders:
current_sandwiches=sandwich_orders.pop() #确保三明治一个一个打出来
print(f'I made your {current_sandwiches}.')
finished_sandwiches.append(current_sandwiches) #打出来之后再加入finish列表。
print("finished sandwiches:")
for finished_sandwich in finished_sandwiches:
print( f'{finished_sandwich}')
7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习7-8而创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while循环将列表sandwich_orders中的'pastrami'都删除。确认最终的列表finished_sandwiches中不包含'pastrami'。
原始:
sandwich_orders=['tuna sandwiches','pastrami','egg sandwiches','pastrami','baconic sandwiches','pastrami']
finished_sandwiches= []
print('Pastrami are sold out.')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_sandwiches.append(sandwich_orders) #打出来之后再加入finish列表。
print("finished sandwiches:")
for finished_sandwich in finished_sandwiches:
print( f'{finished_sandwich}')
结果finished_sandwiches结果 循环了三次。
Pastrami are sold out.
finished sandwiches:
['tuna sandwiches', 'egg sandwiches', 'baconic sandwiches']
['tuna sandwiches', 'egg sandwiches', 'baconic sandwiches']
['tuna sandwiches', 'egg sandwiches', 'baconic sandwiches']
修改:
sandwich_orders=['tuna sandwiches','pastrami','egg sandwiches','pastrami','baconic sandwiches','pastrami']
finished_sandwiches= []
print('Pastrami are sold out.')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_sandwiches = sandwich_orders[:] # 使用切片创建副本
print(f"finished sandwiches:{finished_sandwiches}")
关键:使用切片创建副本。
7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
之前出错的地方:while True(会一直循环)
responses={} #创建集合不是列表
response_active= True
while response_active: #之前写的True,所以一直循环。因为True永远是正确的。
name=input("What's your name?:")
response=input("If you could visit one place in the world, where would you go?:")
responses[name]=response
repeat= input("Would you like to let another person to respond?")
if repeat =='no':
response_active = False
print('\n--Result--')
for name, response in responses.items(): #同时获取值和键
print(f"{response.title()} is {name}'s favorite place.")
在本章中,你学习了:
如何在程序中使用input()来让用户提供信息;如何处理文本和数字输入,以及如何使用while循环让程序按用户的要求不断地运行;多种控制while循环流程的方式:设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素;如何结合使用while循环和字典。