我們在串列那單元提到for迴圈,for迴圈對串列來說是很有效的工具,但for迴圈卻不能修改串列,不然python會很難處理其中的項目,想要遍訪串列又想要修改串列的話,我們就必續用到while迴圈來處理
我們可以用來點餐,將點餐的餐點一一存到要煮的串列中,煮好後再一一的輸出出來
範例如下 :
order=["hamburger","french fries","cola"]
already_cooked=[]
while order : # 如果order串列有東西while迴圈就會繼續執行
cooking=order.pop() # 將order串列的值一一彈出來存到cooking變數中
print("cooking :"+cooking)
already_cooked.append(cooking) # 將cooking變數的值新增到already_cooked串列中
print("Finished :")
for cooked in already_cooked : # 告知python從already_cooked串列中取出值,並將取出的值存到cooked變數中
print(cooked)
輸出結果 :
cooking :cola
cooking :french fries
cooking :hamburger
Finished :
cola
french fries
hamburger
之前我們有提到remove()方法可以刪除特定的值,但remove()能夠順利運作是因為該值在串列只出現一次,當要刪除的值出現很多次的時候,我們就要用while迴圈
範例如下 :
text = ["apple", "banana", "apple", "grape", "apple", "apple", "watermelon"]
while "apple" in text : # 當text串列中含有apple字串時,迴圈就會一直執行
text.remove("apple") # 將text串列中的apple字串移除
print(text)
輸出結果 :
['banana', 'grape', 'watermelon']
我們可以以使用者輸入的方式來把值填入字典中
範例如下 :
response={} # 建立一個空字典
while True:
name=input("What's your name?")
place=input("Where would you want to go?")
response[name]=place # 建立name為鍵place為值的鍵-值對然後存到response字典中
continue_prompt = input("Would you like to let someone else respond? (yes/no)")
if continue_prompt=="no": # 如果continue_prompt=="no"就跳出迴圈
break
for name,place in response.items(): # items()方法會讓for迴圈將每個鍵-值對分別存到name和place的變數中
print(name+" would like to go "+place)
輸出結果 :
What's your name?Bonny
Where would you want to go?Japan
Would you like to let someone else respond? (yes/no)yes
What's your name?Steven
Where would you want to go?Korea
Would you like to let someone else respond? (yes/no)no
Bonny would like to go Japan
Steven would like to go Korea
附上排版較優美的
HackMD網址 :https://hackmd.io/cJfZZPEFQWikbBfmPQDo_A
資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯