python - 如何用两个连续的相同字符串从用户输入中停止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)
推荐阅读
- jenkins - 每当在 Bitbucket Cloud 中创建新分支时,如何触发 Jenkins 作业?
- c# - 修改后的本地 EF Core 实体仍由新查询获取
- struct - Swift UI,从数组中删除项目,同时在其中循环抛出致命错误:索引超出范围
- python - Matplotlib 在 pycharm 中导致运行时错误
- javascript - 在 React 中使用 fluent-ui 构建仪表板,卡片和表格不应该出现在屏幕底部
- php - 循环数组并将值存储在表中
- python - 在 python 烧瓶中使用 CSS
- gams-math - 将系统日期和时间作为字符串写入 gdx
- docker - docker spark集群上容器之间的spark app socket通信
- r - 是否可以在 R 的列名中创建包含空格的数据框?