簡述
for 循環用於針對集合中每個元素的一個代碼塊,而while循環不斷地運行,直到指定的條件不滿足爲止。
例如:
prompt = "\n Tell me something,and i will repeat it back to you."
prompt += "\n Enter 'quit' to end the pragram:"
message = ""
while message != 'quit':
message=input(prompt)
print(message)
執行結果:
使用標誌
在前一個實例中,我們讓程序在滿足指定條件時就執行特定地任務。但是在更復雜的程序中,很多不同的事件都會導致程序停止運行,此時,需要定義一個變量,用於判斷整個程序是否處於活動狀態,整個變量被稱爲標誌。
例如:
prompt = "\n Tell me something,and i will repeat it back to you."
prompt += "\n Enter 'quit' to end the pragram:"
active = True
while active:
message=input(prompt)
if message == 'quit':
active = False
else:
print(message)
輸出結果:
使用用戶輸入來填充字典
可使用while循環提示用戶輸入任意數量的信息。下面創建一個調查程序,其中的循環每次執行時都提示輸入被調查的名字和回答。
例如:
responses ={}
#設置一個標誌,指出調查是否繼續
active = True
while active:
#提示輸入被調查者的名字和回答
name = input("\n請輸入您的名字:")
location = input("\n請輸入您的住址:")
#將答案存儲在字典中
responses[name] = location
#看看是否還有人繼續調查
repeat = input("\n would any other people respond:")
if repeat == 'no':
active = False
#調查結果結束
print("\n-----------調查結果---------------")
for name,location in responses.items():
print(name+"的住址是:"+location)
輸出結果: