while語句初探
示例程式:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 28 16:35:15 2019
@author: cenxi
"""
#while語句
unconfirmed_users=['alice','brain','candace']
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("Verifying user: " + current_user)
confirmed_users.append(current_user)
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
#利用while循環删除指定資料
traffic_tools=['bus','car','bicycle','bus']
print(traffic_tools)
while 'bus' in traffic_tools:
traffic_tools.remove('bus')
print(traffic_tools)
'''
#使用使用者輸入填充字典
responses={}
#設定一個flag
polling_active=True
while polling_active:
name = input('\nWhat is your name?')
reponse = input('Which mountain would you like to climb someday?')
responses[name] = reponse
repeat = input('Would you like to let another person respond?(yes/no)')
if repeat=='no':
polling_active = False
print('\n--- Poll results ---')
for name,response in responses.items():
print(name+' Would like to climb '+ response +'.')
'''
#exercise 1
sandwich_orders=['s','w','o']
finished_sandwichs=[]
while sandwich_orders:
sd_orders=sandwich_orders.pop()
print('I made your '+sd_orders+' sandwich.')
finished_sandwichs.append(sd_orders)
for finished_sandwich in finished_sandwichs:
print(finished_sandwich)
#exercise 2
sandwich_orders=['s','w','o','w']
finished_sandwichs=[]
while sandwich_orders:
sd_orders=sandwich_orders.pop()
print('I made your '+sd_orders+' sandwich.')
finished_sandwichs.append(sd_orders)
for finished_sandwich in finished_sandwichs:
print(finished_sandwich)
while 'w' in finished_sandwichs:
finished_sandwichs.remove('w')
print(finished_sandwichs)
#exercise 3
visit_place={}
flag=True
while flag:
name=input('Please input your name: ')
place=input('\nPlease input where you want to visit: ')
visit_place[name]=place
repeat=input('\nDo you have any other orders?(yes/no)')
if repeat=='no':
flag=False
print('----Ending----')
print(visit_place)
for name in visit_place:
print(name.title()+' wants to visit '+place.title()+'.')
參考
《Python程式設計從入門到實踐》埃裡克.馬瑟斯 著