python第六次練習

例題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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章