Removing break conditions from a concatenated string produced by a loop

Question:

I am trying to print out a concatenated string from a simple, beginner loop but my break conditions keep printing with the final output.

[Here’s my code:]

story = ""
previous_input = None

while True:
    word = str(input("Please type in a word: "))
    story += word + " "
    if word == "end" or word == previous_input:
        break
    previous_input = word
print(story)

[And here is the unintended output which shouldn’t include "end" or the duplicated word which breaks the loop]

Please type in a word: Hey
Please type in a word: come
Please type in a word: over
Please type in a word: end
Hey come over end 

Prints out: Hello world end OR Hello world world – if the loop is broken. How can I keep these loop conditions the same while not printing those final inputs which break the loop? If the answer is really simple maybe just a hint… I know this is insanely basic, super newbie here. Thank you in advance!

Asked By: Mar See

||

Answers:

Check to see if the new word ends the story before adding it to the story.

story = []
while True:
    word = input("Please type in a word: ")
    if word == "end" or story and word == story[-1]
        break
    story.append(word)
print(*story)
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.