python第六次练习

本文通过四个具体实例介绍Python中循环的应用,包括响应用户输入直至特定条件结束的循环、列表元素的转移、列表中重复元素的移除及调查用户梦想度假地等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例题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 + '.')

  结果:
这里写图片描述

发现的问题:

  1. 一个句子太长可以用
    prompt =
    Prompt +=
    的方式
  2. 如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
  3. 不要忘记冒号
  4. Input(prompt)
  5. Remove删掉第一个列表中的该元素
    While ‘alice’ in users:
    Users.remove(‘alice’)
  6. 7-5 7-6 7-10
  7. 使用active
  8. sandwich_orders.remove()不要只写remove()
  9. 不要忘记.items()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值