当用户输入相同的值两次时如何停止循环?

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

当用户输入“end”并且输入相同的单词两次时,我想停止这个程序。例如:

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
attempts = 0
sentence =""
while True:
    word = input("Please type in a word: ")
    if word == "end":
        break
            
    sentence += word + " "
    attempts += attempts
    
    
print(sentence)
python python-3.x loops while-loop user-input
1个回答
0
投票

您可以使用一组来跟踪到目前为止输入的单词。

例如:

attempts = 0
sentence = ""
word_set = set()

while True:
    word = input("Please type in a word: ")

    if word == "end":
        break

    if word in word_set:
        print("You've already entered that word. Please enter a different word.")
    else:
        word_set.add(word)
        sentence += word + " "
        attempts += 1

print(sentence)
© www.soinside.com 2019 - 2024. All rights reserved.