天天看點

break 和continue 使用while 循環來處理清單和字典 while -else

函數input() 的工作原理,input() 接受一個參數:即要向使用者顯示的提示 或說明,讓使用者知道該如何做。在這個示例中,Python運作第1行代碼時,使用者将看到提示Tell me something, and I will repeat it back to you: 。程式等待使用者輸入,并在使用者按Enter鍵後繼續運作。輸入存儲在變量message 中,接下來的print(message) 将輸入呈現給使用者:

message = raw_input("Tell me something, and I will repeat it back to you: ")

print(message)

Tell me something, and I will repeat it back to you: Hello everyone!

Hello everyone!

while 循環簡介

for 循環用于針對集合中的每個元素都一個代碼塊,而while 循環不斷地運作,直到指定的條件不滿足為止。

prompt = “\nTell me something, and I will repeat it back to you:”

prompt += "\nEnter ‘quit’ to end the program. "

message = “”

while message != ‘quit’:

message = raw_input(prompt)

print message

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello everyone!

Hello everyone!

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. Hello again.

Hello again.

Tell me something, and I will repeat it back to you:

Enter ‘quit’ to end the program. quit

quit

這個程式很好,唯一美中不足的是,它将單詞’quit’ 也作為一條消息列印了出來.

使用break 退出循環

要立即退出while 循環,不再運作循環中餘下的代碼,也不管條件測試的結果如何,可使用break 語句。break 語句用于控制程式流程,可使用它來控制哪些代碼行将執行,

哪些代碼行不執行,進而讓程式按你的要求執行你要執行的代碼。

例如,來看一個讓使用者指出他到過哪些地方的程式。在這個程式中,我們可以在使用者輸入’quit’ 後使用break 語句立即退出while 循環:

prompt = “\nPlease enter the name of a city you have visited:”

prompt += "\n(Enter ‘quit’ when you are finished.) "

while True:

city = input(prompt)

if city == ‘quit’:

break

else:

print("I’d love to go to " + city.title() + “!”)

以while True 打頭的循環将不斷運作,直到遇到break 語句。這個程式中的循環不斷輸入使用者到過的城市的名字,直到他輸入’quit’ 為止。使用者輸入’quit’

後,将執行break 語句,導緻Python退出循環:

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) New York

I’d love to go to New York!

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) San Francisco

I’d love to go to San Francisco!

Please enter the name of a city you have visited:

(Enter ‘quit’ when you are finished.) quit

list.pop 可以指定pop哪一項(預設最後一項)會傳回pop的值

list.remove 僅删除

Python List sort()方法

list.sort(cmp=None, key=None, reverse=False)

參數

cmp -- 可選參數, 如果指定了該參數會使用該參數的方法進行排序。
key -- 主要是用來進行比較的元素,隻有一個參數,具體的函數的參數就是取自于可疊代對象中,指定可疊代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序, reverse = False 升序(預設)。
           

在循環中使用continue

要傳回到循環開頭,并根據條件測試結果決定是否繼續執行循環,可使用continue 語句,它不像break 語句那樣不再執行餘下的代碼并退出整個循環。continue 語句,讓Python忽略餘下的代碼,并傳回到循環的開頭

break 和continue 使用while 循環來處理清單和字典 while -else
break 和continue 使用while 循環來處理清單和字典 while -else