如何停止带有两个连续相同字符串的while循环形成用户输入,然后打印出其余字符串



我是一个完全的初学者,目前正在学习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)

最新更新