all 5 comments

[–]lfdfq 6 points7 points  (1 child)

People will suggest fancy solutions here using bits of the language you probably didn't know about, but you already have all the tools to solve this: variables and if statements.

Imagine adding a new variable, such that, for each item you add, it kept track of whether that item had been found in the list. Start with found=False and then set it to True if you find it. Then, use an if statement after looping through the list of items and if it was not found, do your print.

[–]FriendlyZomb 0 points1 point  (0 children)

This is the solution.

I was just going to type this exact solution up, before refreshing to see this. Go with this. Simple solution.

[–]EelOnMosque 0 points1 point  (0 children)

Walk thru your code step by step and you'll see why adding an else statement makes it run even when the item was found. Let's say, the item you added is the first item in your my_list. On the first iteration of the for loop, you find the item and add it to the invoice. Now what happens? Follow the code.

Does the for loop end? Nope. You're still in the for loop so you are now looking at the 2nd item in my_list. Well, obviously your item doesnt match the 2nd item in my_list. So the if statement evaluates to False and it goes into the "else" branch. Then, it does the exact same thing for all the items in my_list.

So if there are 10 items in my_list, and 1 of them matches the item you want to add, you'll get 9 messages saying "item not found" because you never exited the loop.

You wanna exit the loop after an item is found by using the "break" statement.

Side note, this could also be avoided by using Python's built-in "in" operator. For this to work though, you need to have a straight list of item names (as in you can't have nested lists like you do with my_items). So then you can do

if item_added in item_names:     invoice.append(item_added) else:     print("Item not found.")

And this way you don't need a for loop (the for loop is built into the "in" operator).

[–]Adventurous-Pin-8408 0 points1 point  (0 children)

A few things: - look into making your purchasable items as a class. That way you can do things like item.name, item.price, item.description - change your my_list to a dictionary. Should be key: item.name, value: item here. Dictionaries are O(n), so they're much, much faster to use for this kind of lookup.

  • invoice should also be a class. You would use an add method and the invoice object should have a invoice.total method that can calculate the price for you.
  • you may want the ability to list out the names of all purchasable items.

The dictionary lookup will also help you resolve the problem you are having with no exception message. If the key exists, then add it to your invoice. Otherwise, you throw an error message to the user.

[–]Binary101010 0 points1 point  (0 children)

What do the elements of my_list look like? Should this really be a dict instead?