第六章:用户输入和while循环

前言
在本章中,你将学习如何接受用户输入,让程序能够对其进行处理。在程序需要一个名字时,你需要提示用户输入该名字;程序需要 一个名单时,你需要提示用户输入一系列名字。为此,你需要使用函 数input()。
你还将学习如何让程序不断地运行,让用户能够根据需要输入信息,并在程序中使用这 些信息。为此,你需要使用while循环让程序不断地运行,直到指定的条件不满足为止。
通过获取用户输入并学会控制程序的运行时间,可编写出交互式程序。
7.1 函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在 一个变量中,以方便你使用。

message = input("Tell me something,and I will repeat it back to you:")
print(message)

7.1.2 使用int()来获取数值输入
使用函数input()时,Python将用户输入解读为字符串;但如果你试图将输入作为数字使用,就会引发错误:为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符 串表示转换为数值表示;

height = input("How tall are you,in inches?")
height = int(height)	#转化为数值

if height >= 36:
	print("\nYou're tall enough to ride!")
	
else:
	print("\nYou'll be able to ride when you're a little older.")
	

7.1.3 求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少。如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。你可利用这一点来判断一个数是奇数还是偶数:

number = input("Enter a number,and I'll tell you if it's even or odd:")
number = int(number)

if number%2 == 0:
	print("\nThe number "+str(number)+" is even.")
else:
	print("\nThe number "+str(number)+" is odd.")

7.1.4 在Python 2.7中获取输入
如果你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。这个函数与Python 3 中的input()一样,也将输入解读为字符串.Python 2.7也包含函数input(),但它将用户输入解读为Python代码,并尝试运行它们。因此,最好的结果是出现错误,指出Python不明白输入的代码;而最糟的结果是,将运行你原本无意运 行的代码。如果你使用的是Python 2.7,请使用raw_input()而不是input()来获取输入。
课后习题
7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息, 如“Let me see if I can find you a Subaru”。
7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过 8人,就打印一 条消息,指出没有空桌;否则指出有空桌。
7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是 10的整数倍。

#7-1
car = input("请问你要租赁什么样的汽车:")
print("Let me see if I can find you a "+car)

#7-2
num = input("请输入您的用餐人数:")
num = int(num)
if num >= 8:
	print("抱歉没有空桌子了")
else:
	print("欢迎光临!")

#7-3
number = input("请输入一个数字:")
number = int(number)
if number%10 == 0:
	print(str(number)+"是10的倍数!")
else:
	print("不是10的倍数!")

7.2 while 循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条 件不满足为止。
7.2.1 使用while循环
你可以使用while循环来数数,例如下面的while循环从1数到5:

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。
只要满足条件current_number <= 5,Python就接着运行这个循环。由于1小于5,因此Python 打印1,并将current_number加1,使其为2;由于2小于5,因此Python打印2,并将current_number 加1,使其为3,以此类推。一旦current_number大于5,循环将停止,整个程序也将到此结束:

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)

7.2.3 使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于 活动状态。这个变量被称为标志

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)
active = True
while active:
	message = input(prompt)
	if message == 'quit':
		active = False
	else:
		print(message)

7.2.4 使用break 退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break语句。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()+"!")

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循环都必须有停止运行的途径,这样才不会没完没了地执行下去

x = 1 
while x <= 5:     
	print(x)     
	x += 1 

如果不小心遗漏了代码行x += 1,这个循环将没完没了地运行。如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
课后习题
7-4 **比萨配料:**编写一个循环,提示用户输入一系列的比萨配料,并在用户输入 'quit’时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添 加这种配料。
7-5 **电影票:**有家电影院根据观众的年龄收取不同的票价:不到 3岁的观众免费; 3~12岁的观众为 10美元;超过 12岁的观众为 15美元。请编写一个循环,在其中询问 用户的年龄,并指出其票价。
7-6 三个出口:以另一种方式完成练习 7-4或练习 7-5,在程序中采取如下所有做法。
 在 while 循环中使用条件测试来结束循环。
 使用变量 active 来控制循环结束的时机。
 使用 break 语句在用户输入’quit’时退出循环。
7-7 无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按 Ctrl +C, 也可关闭显示输出的窗口)。

#7-4
prompt = "\n请输入你需要的原材料:"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':
	message = input(prompt)
	if message!= 'quit':
		print("我们会在比萨中添加:"+message)

#7-5
prompt = "\nplease enter your age,and then I will tell you how much you pay!"
prompt += "\nEnter 'quit' to end the program."
age = input(prompt)

if age == 'quit':
	breakpoint()
if int(age) < 3:
	print("Your cost is $0.")
elif int(age)<=12:
	print("Your cost is $10.")
else:
	print("Your cost is $15.")

#7-6
# use condition testing
age = input('How old are you?\n')
while age != "quit":
    if int(age) < 3:
        print("Free.")
    elif int(age) > 12:
        print("15 dollars, please.")
    elif int(age) >= 3 and int(age) <= 12:
        print("10 dollars, please.")
    age = input('How old are you?\n')

# use variable "active"
active = 1
while active:
	age = input("How old are you?\n")
	if age == 'quit':
		active = 0
	else:
		if (int(age)<3):
			print("free")
		elif(int(age)>12):
			print("15 dollars,please.")
		else:
			print("10 dollars,please.")

#use 'break' statement
active = 1
while active:
	age = input("How old are you?\n")
	if age == 'quit':
		break
	else:
		if (int(age)<3):
			print("free")
		elif(int(age)>12):
			print("15 dollars,please.")
		else:
			print("10 dollars,please.")
			
#7-7
i = 0
while True:
	i +=1
	print("I love you!")
	print(i)

7.3 使用while 循环来处理列表和字典
到目前为止,我们每次都只处理了一项用户信息:获取用户的输入,再将输入打印出来或作 出应答;循环再次运行时,我们获悉另一个输入值并作出响应。然而,要记录大量的用户和信息, 需要在while循环中使用列表和字典。
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以 跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列 表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
7.3.1 在列表之间移动元素
假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移 到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验 证用户列表中提取出来,再将其加入到另一个已验证用户列表中。

# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brain','candace']
confirmed_user = []

# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
	current_user = unconfirmed_users.pop()
	print("Verifying user:"+current_user.title())
	confirmed_user.append(current_user)
	
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_user:
	print(confirmed_user.title())

7.3.2 删除包含特定值的所有列表元素
在第3章中,我们使用函数remove()来删除列表中的特定值,这之所以可行,是因为要删除 的值在列表中只出现了一次。如果要删除列表中所有包含特定值的元素,该怎么办呢?
假设你有一个宠物列表,其中包含多个值为’cat’的元素。要删除所有这些元素,可不断运 行一个while循环,直到列表中不再包含值’cat’,如下所示:

#7.3.2 删除包含特定值的所有列表元素
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 place 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 result...")
for name,response in responses.items():
	print(name+" would you like to climb "+response+".")

课后习题
7-8 熟食店:创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名 字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders,对于 其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表 finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习 7-8 而创建的列表 sandwich_orders,并确保’pastrami’在其中至少出现了三次。在程序开头附近添加这样 的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将 列表 sandwich_orders 中的’pastrami’都删除。确认最终的列表 finished_sandwiches 中 不包含’pastrami’。
7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调 查结果的代码块。

#7-8
sandwich_orders = ['huanxi','kele','KFC']
finished_sandwiches = []
for sandwich_order in sandwich_orders:
	print("I made your "+sandwich_order+ " sandwich.")
	finished_sandwiches = sandwich_orders
print("\n您的所有三明治都做好了!")
print(finished_sandwiches)

#7-9
sandwich_orders = ['pastrami','keke','KFC','pastrami','lily','pastrami','haha']
print("熟食店的五香熏牛肉卖完了")
while 'pastrami' in sandwich_orders:
	sandwich_orders.remove('pastrami')
print(sandwich_orders)

#7-10
prompt = input("If you could visit one place in the world,where would you go?")
print("hello!,you'd like to go "+prompt)

7.4 小结
在本章中,你学习了:如何在程序中使用input()来让用户提供信息;如何处理文本和数字 输入,以及如何使用while循环让程序按用户的要求不断地运行;多种控制while循环流程的方式: 设置活动标志、使用break语句以及使用continue语句;如何使用while循环在列表之间移动元素, 以及如何从列表中删除所有包含特定值的元素;如何结合使用while循环和字典。
下一章,将继续学习函数!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kaichu2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值