两次输入相同值时如何结束while循环?

问题描述 投票:0回答:3

如何编写一个 while 循环,要求用户输入,并在连续使用同一值两次时中断?

这是我当前的尝试,尝试使用

len(set(word))
来获取前一个单词:

story = ""

while True:
    word = input("Give me a word: ")
    if word == "end" or word == len(set(word)):
        break
    story += word + " "

print(story)
python input while-loop
3个回答
3
投票

连续两次,我只会记住前一个单词

story = ""
prev = ""

while True:

    word = input("Give me a word: ")

    if word == "end" or word == prev:

        break

    prev = word
    story += word + " "

print(story)

0
投票

我会这样做:

story = []
prev = ""

while True:

    word = input("Give me a word: ")

    if word == "end" or word == prev:

        break

    prev = word
    story.append(word+" ")

print(''.join(story))

0
投票
'''Program to take single word as input from users, 
combine input word as a string and end the program
if any of the word in the string is repeated'''
import re
storyString = ""

def takeInput(storyString):
    global inputWord 
    inputWord = input("Give me a word: ")
    creatWordFromString(storyString)

def creatWordFromString(storyString):
    storyList = storyString.split()
    if inputWord in storyList:
        exit()
    else:
        storyList.append(inputWord)
        storyString =' '.join(storyList)
        print(storyString)
        takeInput(storyString)
    
takeInput(storyString)
© www.soinside.com 2019 - 2024. All rights reserved.