Molly W
Molly W

Reputation: 27

Python adding multiple items to a list

I have to write a program that asks the user to enter their shopping list, it should ask them to enter their first item for their list and to enter 'END' when they have entered all of their items.

This is my code so far:

#Welcome
name = input("What is your name? ")
print("Welcome %s to your shopping list" %name)
#Adding to the list
shoppingList = []
shoppingList.append = input(print("Please enter the first item of your shopping list and type END when you have entered all of your items: "))
length = len(shoppingList)
#Output
print("Your shopping list is", length, "items long")
shoppingList.sort
print(shoppingList)

I'm not to sure how to fix the adding to the list second, could you help? Thanks.

Upvotes: 0

Views: 5108

Answers (3)

Barry
Barry

Reputation: 303870

You are assigning to the append method. What you want to do is assign to the actual list:

shoppingList = [item for item in input(print("....")).split()][:-1]

The [:-1] there is to drop the END. Or you can make it a filter

shoppingList = [item for item in input(print("....")).split() if item != 'END']

Upvotes: 1

isharacomix
isharacomix

Reputation: 161

Append is a function, so you should be calling it like this.

shoppingList.append("Bread")

However, in order to add more than one item, you'll need some kind of a loop.

while True:
    new_item = input(print("Please enter an item of your shopping list and type END when you have entered all of your items: "))
    if new_item == "END": break
    shoppingList.append(new_item)

This loop appends each string that is not "END" to the list. When "END" is entered, the loop ends.

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19763

add while and check for End:

shopingList = []
end =''
while end.lower() != 'end':
    item = input("Please enter the item of youi shopping list and type END when you have entered all of your items: ")
    shopingList.append(item)
    end = item

There is no need of print statement inside input

in the above code, i am checking if the user enters end it will come of the while loop.
varible item will store the user input and append it to the shopingList, end variable is updated with user item as in while end variable is compared with string 'end'

Upvotes: 0

Related Questions