当用户输入“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)
您可以使用一组来跟踪到目前为止输入的单词。
例如:
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)