简体   繁体   中英

Saving User Inputs into a List in Python 3.5.1

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"):

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']

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM