while循环真的让我很困惑。它说while循环将在条件为True时执行。那么,根据下面的算法,只有当我们没有输入"quit"时,消息才会被打印出来,对吗?然而,当我输入'quit'时,quit仍然在结束循环之前被打印出来。
为什么?有关于while循环的介绍吗?谢谢!
prompt = "Please let me know what toppings you prefer?"
prompt += "Enter 'quit' to end the order. "
message = ""
while message != 'quit':
message = input (prompt)
print (message)
是的,这是假定的行为,因为检查while条件只会在每次循环完成时发生。
while message != 'quit': #3. Loop again for condition checking here
message = input (prompt) #1. Your input is 'quit' here
print (message) #2. 'quit' gets printed
#4. found that the condition is false and finally breaks the loop
所以对于你的情况,我猜是你不想在控制台上输入'quit'后打印'quit'消息,你可以这样做:
while True:
message = input (prompt)
if message == 'quit':
break
else:
print(message)
使用一个永远连续的循环,但在其内部进行条件检查,并在条件满足时使用break
关键字。
你可以试试这个
# This code creates an empty list called "prompts" and then appends two strings
# to it, representing prompts for the user.
prompts =[]
prompts.append("Please let me know what toppings you prefer?")
prompts.append("Enter 'quit' to end the order. ")
# An empty list called "responses" is created to store the user's input
responses = []
# The code enters a while loop which will continue until the string 'quit'
# is entered by the user
while 'quit' not in responses:
# for each prompt in the prompts list, the code will ask the user for input
# and append the input to the responses list
for prompt in prompts:
responses.append(input(prompt))
第一次执行while循环时,message
变量不等于"quit"
,因此内部部分将执行
你可能想这样做:
prompt = "Please let me know what toppings you prefer?Enter 'quit' to end the order. "
while message:=input(prompt) != "quit": print(message)
使用python 3.8版本
中的walrus操作符