- 讓用戶選擇何時退出
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
示例輸出:
讓用戶選擇何時退出
- 使用標(biāo)志
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
action = True
while action:
message = input(prompt)
if message == "quit":
action = False
else:
print(message)
示例輸出:
使用標(biāo)志
- 使用 break 退出循環(huán)
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
while True:
message = input(prompt)
if message == "quit":
break
else:
print(message)
- 在循環(huán)中使用 continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
示例輸出:
在循環(huán)中使用 continue
- 在列表之間移動元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
示例輸出:
在列表之間移動元素
- 刪除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
- 使用用戶輸入來填充字典
responses = {}
while True:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
break
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
示例輸出:
使用用戶輸入來填充字典
本文參考自 《Python 編程:從入門到實踐》