Reputation: 13
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)
Upvotes: 0
Views: 1609
Reputation: 56
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)
Upvotes: 3
Reputation: 395
'''Program to take single word as input from users,
combine input word as a string and end the program
if any of the word in the string is repeated'''
import re
storyString = ""
def takeInput(storyString):
global inputWord
inputWord = input("Give me a word: ")
creatWordFromString(storyString)
def creatWordFromString(storyString):
storyList = storyString.split()
if inputWord in storyList:
exit()
else:
storyList.append(inputWord)
storyString =' '.join(storyList)
print(storyString)
takeInput(storyString)
takeInput(storyString)
Upvotes: 0
Reputation:
I would do this:
story = []
prev = ""
while True:
word = input("Give me a word: ")
if word == "end" or word == prev:
break
prev = word
story.append(word+" ")
print(''.join(story))
Upvotes: 0