Python编程:从入门到实践(埃里克·马瑟斯)第七章部分习题

练习 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值