Richard
Richard

Reputation: 13

Appending a list in python + Validation of inputted data

I'm having trouble adding items to a list from a user's input, I think you can see what I'm trying to do here, I want the user to be able to add items to a list, and have it displayed afterwards. Criteria: It must contain a FOR loop and some form of data validation.

def main():
    num=int(input("How many values would you like in your list?"))
    for x in range(num)
        myList=[]
        newValue=input("Enter the text you would like to add")
        myList.append(newValue)
    print(myList)

Upvotes: 0

Views: 440

Answers (4)

Anthony Pham
Anthony Pham

Reputation: 3106

Well, you have multiple mistakes:

  • You are missing a colon in the for loop

  • Since you reassign myList to an empty list every single iteration of the for loop, the list will only have one value in the end

  • You actually need to call the function

Thus the code becomes:

def main():
    num=int(input("How many values would you like in your list?"))
    myList = []               # Create the list here instead
    for x in range(num):      # Colon is needed
        newValue = raw_input("Enter the text you would like to add: ")
        myList.append(newValue)
    print(myList)

main()                        # Call the function

Upvotes: 0

Gurupad Mamadapur
Gurupad Mamadapur

Reputation: 989

The problem

You are initializing the list every time as myList = [] inside the loop. Whatever data you appended is lost.

Also, : is missing after range(num).

Solution

Simply initialize it outside the loop.

def main():
    num=int(input("How many values would you like in your list?"))
    myList=[] # This needs to be initialized outside the loop 
    for x in range(num):
        newValue=input("Enter the text you would like to add")
        myList.append(newValue)
    print(myList)

if __name__ == '__main__':
    main()

Upvotes: 1

Chris Nikolopoulos
Chris Nikolopoulos

Reputation: 1

One problem in your code is that for needs : at the end.

But the main one is that you are reseting your myList to an empty list at the start of each iteration... as a result, anything you input is going to be appended in an empty list (so the result of a single-valued list).

Upvotes: 0

nguaman
nguaman

Reputation: 971

try this!

def main():
    num=int(raw_input("How many values would you like in your list? "))
    myList=[]
    for x in range(num):
        newValue = raw_input("Enter the text you would like to add ")
        myList.append(newValue)
    print(myList)

Upvotes: 0

Related Questions