练习 7-2:餐馆订位 编写一个程序,询问用户有多少人用餐。如果超过 8 位,就 打印一条消息,指出没有空桌;否则指出有空桌。
num = input('How many people are dining?')
num = int(num)
if num > 8:
print('Sorry, the restaurant is out of seats.')
else:
print('There are seats available here.')
练习 7-5:电影票 有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众 免费;3~12 岁的观众收费 10 美元;超过 12 岁的观众收费 15 美元。请编写一个循环, 在其中询问用户的年龄,并指出其票价。
prompt = "How old are you?"
prompt += "\nEnter 'quit' to leave. "
# 使用 break 语句在用户输入'quit'时退出循环
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print(" You get in free!")
elif age < 13:
print(" Your ticket is $10.")
else:
print(" Your ticket is $15.")
练习 7-6:三种出路 以不同的方式完成练习 7-4或练习 7-5,在程序中采取如下做法。
- 在 while 循环中使用条件测试来结束循环。
- 使用变量 active 来控制循环结束的时机。
- 使用 break 语句在用户输入'quit'时退出循环
# 在while循环中使用条件测试来结束循环
prompt = "How old are you?"
prompt += "\nEnter 'quit' to leave. "
age = ''
while age != 'quit':
age = input(prompt)
if age != 'quit':
age = int(age)
if age < 3:
print(" You get in free!")
elif age < 13:
print(" Your ticket is $10.")
else:
print(" Your ticket is $15.")
# 使用变量 active 来控制循环结束的时机。
prompt = "How old are you?"
prompt += "\nEnter 'quit' to leave. "
active = True
while active:
age = input(prompt)
if age == 'quit':
active = False
else:
age = int(age)
if age < 3:
print(" You get in free!")
elif age < 13:
print(" Your ticket is $10.")
else:
print(" Your ticket is $15.")
练习 7-8:熟食店 创建一个名为 sandwich_orders 的列表,在其中包含各种三明 治的名字,再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders, 对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到 列表 finished_sandwiches 中。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['A_sandwich', 'B_sandwich', 'C_sandwich']
finished_sandwiches = []
while sandwich_orders:
current_order = sandwich_orders.pop()
print(f"I made your {current_order}.")
finished_sandwiches.append(current_order)
for finished_sandwich in finished_sandwiches:
print(f"{finished_sandwich} has been made.")
练习 7-9:五香烟熏牛肉卖完了 使用为完成练习 7-8而创建的列表 sandwich_orders, 并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条 消息,指出熟食店的五香烟熏牛肉(pastrami)卖完了;再使用一个 while 循环将列表 sandwich_orders 中的'pastrami'都删除。确认最终的列表 finished_sandwiches 未包含 'pastrami'。
sandwich_orders = ['A_sandwich', 'B_sandwich', 'C_sandwich', 'pastrami', 'pastrami']
print("The pastrami was sold out")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami') # 删除'pastrami'
print(sandwich_orders)