首页 > 解决方案 > 如何用两个连续的相同字符串从用户输入中停止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)

标签: pythonstringwhile-loop

解决方案


要使用两个连续的单词停止循环,您可以使用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)

推荐阅读