Reputation: 83
I want to prompt the user for a list of phrases over and over again until they input END
and save all of the user's inputs into a list. How can I do that?
My code so far:
print("Please input passwords one-by-one for validation.")
userPasswords = str(input("Input END after you've entered your last password.", \n))
boolean = True
while not (userPasswords == "END"):
Upvotes: 0
Views: 1036
Reputation: 22282
You can simply use iter(input, 'END')
, which returns a callable_iterator
. Then we can use list()
to get a real list:
>>> l = list(iter(input, 'END'))
foo
bar
foobar
END
>>> l
['foo', 'bar', 'foobar']
About how does it work, if you take a look at help(iter)
:
iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
You can also use a while
loop if you think it's more simple and clear anyway:
l = []
while True:
password = input()
if password != 'END':
l.append(password)
else:
break
Demo:
>>> l = []
>>> while True:
... password = input()
... if password != 'END':
... l.append(password)
... else:
... break
...
...
...
foo
bar
END
>>> l
['foo', 'bar']
Upvotes: 4
Reputation: 1292
One way to do is with a while loop
:
phraseList = []
phrase = input('Please enter a phrase: ')
while phrase != 'END':
phraseList.append(phrase)
phrase = input('Please enter a phrase: ')
print(phraseList)
Result:
>>> Please enter a phrase: first phrase
>>> Please enter a phrase: another one
>>> Please enter a phrase: one more
>>> Please enter a phrase: END
>>> ['first phrase', 'another one', 'one more']
Upvotes: 2