for requested_topping in requested_toppings: if requested_topping in available_toppings: print('Adding ' + requested_topping + '.') else: print("Sorry, we don't have " + requested_topping + '.')
print('\nFinished making your pizza!')
Adding mushrooms.
Sorry, we don't have french fish.
Adding extra cheese.
Finished making your pizza!
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,word!
Hello,word!
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit
quit
1 2 3 4 5 6 7 8
prompt = "\nTell me sth, and I'll repeat it back to you: " prompt += "\nEnter 'quit' to end program."
message = " " while message != 'quit': message = input(prompt) if message != 'quit': print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!
Hello,world!
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit
prompt = "\nTell me sth, and I'll repeat it back to you: " prompt += "\nEnter 'quit' to end program."
active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!
Hello,world!
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit
2.3 使用break退出循环
1 2 3 4 5 6 7 8 9
prompt = "\nTell me sth, and I'll repeat it back to you: " prompt += "\nEnter 'quit' to end program."
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!
Hello,world!
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit
2.4 在循环中使用continue
1 2 3 4 5 6
current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number)
while polling_active: # 提示用户输入调查者的名字和回答 name = input("\nWhat's 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': polling_active = False
# 调查结束,显示结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(f"{name.title()} would like to climb {response.title()}.")
What's your name? jack
Which mountain would you like to climb someday? jinyun mountain
Would you like to let another person respond? (yes/no) no
--- Poll Results ---
Jack would like to climb Jinyun Mountain.