[Python] Python Beginner lesson: end sentence if word repeated

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    Change the program so that the loop ends also if the user types in the same word twice in a row.

    Sample output
    Please type in a word: It
    Please type in a word: was
    Please type in a word: a
    Please type in a word: dark
    Please type in a word: and
    Please type in a word: stormy
    Please type in a word: night
    Please type in a word: night
    It was a dark and stormy night


    So this question has two parts. The first part I was able to figure out. 2nd part, not so much. I have added a variable to store the inputted word, but I just can't get it to exit loop when "word == stop"

    words = ""
    stop = ""
    while True:
    word = input("Please type in a word")
    if word == "end":
    break
    if stop == word:
    break
    words += f"{word} "
    print(words)



    So with inputs: Hello, my, name, is, end:

    I get outputs Hello, my, name, is

    This is expected and satisfies question 1. Question 2 wants me to end it if a word is repeated. Above is my attempt that doesn't seem to work. Please no arrays or lists, I know this can be done using that, but as this is a beginner course, and we have not yet learned about those, I am to solve using above methodology.

    Continue reading...

Compartilhe esta Página