简体   繁体   中英

Appending multiple user inputs to a list

I would like to know how I can take multiple user inputs and append each input to a list. For example, the user is asked how many times they would like to send a message. If they specify 3, then they are presented with three inputs which are later appended to the list.

I have tried several different ways to do this however I only ever see the last input appended to the list rather than the multiple inputs.

List = []
total = (int(input('How many?: ')))
for _ in range(total):
    messages = input('> ')
List.append(messages)

print (List)

You did great actually, just need to indent List.append(messages) to include it in the loop code, otherwise you'll be appending the last message only to the list or (in the worst scenario where total is 0) you'll get a not defined error .

List = []
total = (int(input('How many?: ')))
for _ in range(total):
    messages = input('> ')
    List.append(messages)

print (List)
n = input('How many?: ')
l = [raw_input('> ') for i in range(n)]

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