我是一个完全的初学者,目前正在学习python的在线课程来挑战自己,可以说我已经碰壁了。我想知道如何使用单词stop或两个连续的相同单词来停止while循环。这是我目前拥有的代码:
all = "" #store variable
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
all += entry + " " # add to list
print(all)
要停止带有两个连续单词的循环,可以使用split
获取输入的最后一个单词,并将其与当前单词进行比较。
试试这个代码:
all = "" # store variable
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
if len(all) and all.split()[-1] == entry: # if same as last word
break
all += entry + " " # add to list
print(all)