您的位置:首页 > 编程语言 > Python开发

《python编程从入门到实践》总结及课后答案-第7章 用户输入和while循环(2)

2019-07-29 10:43 537 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/xinglingdi/article/details/97624942
  • 使用 while 循环来处理列表和字典

for 循环是一种遍历列表的有效方式,但在 for 循环中不应修改列表,否则将导致 Python 难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环。

例如:假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?

[code]unconfirmed_users = ['gun', 'grunt', 'dt']
confirmed_users = []

while unconfirmed_users:
current_user = unconfirmed_users.pop()

print("Verifying user:", current_user.title())
confirmed_users.append(current_users)

print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print("\t", confirmed_user)

使用函数 remove() 来删除列表中的特定值。如果列表中只有一个时,只使用一次remove()函数即可,如果有多个呢,这时候就可以使用while循环。例如:

[code]pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
pets.remove('cat')

print(pets)

7-8  熟食店 :创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders ,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich ,并将其移到列表 finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。

[code]sandwich_orders = ['meat sandwich', 'fruit sandwich', 'huotui sandwich']
finished_sandwiches = []

while sandwich_orders:
making = sandwich_orders.pop()
print("I made your " + making)
finished_sandwiches.append(making)

print("\nAll sandwiches have been made: ")
for sandwich in finished_sandwiches:
print("\t" + sandwich)

7-9  五香烟熏牛肉( pastrami )卖完了 :使用为完成练习 7-8 而创建的列表 sandwich_orders ,并确保 'pastrami' 在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将列表 sandwich_orders 中的 'pastrami' 都删除。确认最终的列表 finished_sandwiches 中不包含 'pastrami' 。

[code]sandwich_orders = ['pastrami','meat sandwich', 'pastrami','fruit sandwich', 'huotui sandwich','pastrami']
finished_sandwiches = []

print("Pastrami has sold out.")

while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')

while sandwich_orders:
making = sandwich_orders.pop()
print("I made your " + making)
finished_sandwiches.append(making)

print("\nAll sandwiches have been made: ")
for sandwich in finished_sandwiches:
print("\t" + sandwich)

7-10  梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于 “If you could visit one place in the world, where would you go?” 的提示,并编写一个打印调查结果的代码块。 

[code]vacation_places = {}
active = True

while active:
name = input("\nWhat is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
ask = input("Do you want to continue investigating? (yes/no) ")

vacation_places[name] = place

if ask == 'no':
active = False

print("\n--- Results ---")
for name, place in vacation_places.items():
print(name.tile() + ': ' + place)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐