pythoninputwhile-loop

How to end while loop when same value is inputted twice?


How can I write a while loop that asks for a user for input, and breaks when the same value is used twice in a row?

This is my current attempt, which tries to use len(set(word)) to get the previous word:

story = ""

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

print(story)

Solution

  • For twice in a row, I would just keep track of the previous word and break if it matches the new one.

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