例题7-4
描述:编写一个在用户输入quit后结束的循环。
代码:
prompt = 'Please enter the pizza toppings '
prompt += '\n(Enter "quit" if you finish):'
while True:
toppings = input(prompt)
if toppings == 'quit':
break
print('We will add ' + toppings + ' to the pizza.')
结果:
例题7-8
描述:使用while实现列表转移。
代码:
sandwich_orders = ['Mini Sandwich', 'Jagabe Sandwich', 'Tuna Sandwich']
finished_sandwiches = []
while sandwich_orders:
sandwich = sandwich_orders.pop()
print('I made your ' + sandwich + '.')
finished_sandwiches.append(sandwich)
print('All sandwiches are finished: ')
for sandwich in finished_sandwiches:
print(sandwich)
结果:
例题7-9
描述:使用while将一个列表中多个重复的指定元素删除。
代码:
sandwich_orders = ['pastrami', 'jagabe', 'tuna', 'pastrami', 'pastrami']
print('Pastrami sandwiches are sold out!')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
结果:
例题7-10
描述:编写一个程序,调查用户梦想度假地,包括提示语句和结果。
代码:
responses = {}
polling_active = True
while polling_active:
name = input('\nWhat is your name? ')
prompt = 'If you could visit one place in the world, '
prompt += 'where would you go?'
response = input(prompt)
responses[name] = response
repeat = input('Would you like another person to respond? (yes/no)')
if repeat == 'no':
polling_active = False
print('\n--- Poll Results ---')
for name,response in responses.items():
print(name + ' would go to ' + response + '.')
结果:
发现的问题:
- 一个句子太长可以用
prompt =
Prompt +=
的方式 - 如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
- 不要忘记冒号
- Input(prompt)
- Remove删掉第一个列表中的该元素
While ‘alice’ in users:
Users.remove(‘alice’) - 7-5 7-6 7-10
- 使用active
- sandwich_orders.remove()不要只写remove()
- 不要忘记.items()