Search code examples
pythonpython-3.xfor-loopif-statementbreak

Python program - returning every response from a loop instead of just the desired one


I have the following Python program and want the program to simply return the price of the corresponding item in the list 'items'. Instead, as you can see, it doesn't work correctly and either breaks or returns "There is no such item" and then the number. I have tried various things and can't get the sequence of output right.

https://trinket.io/python/77909a6574

Desired output:

User enters: Chicken Wings
Output: 5

User enters: Jollof Rice
Output: 7

and so on.

Can anyone suggest a fix as well as best practice for using an if statement inside a for loop and breaking out at the right time.

def salestracker():
  print("---Sales Tracker---")
  print("---MENU---")
  print("""
  1. Find the price of an item
  2. Enter sales of an item
  3. Find total of the day
  
  """)
  
  items=["Chicken Wings","Jollof Rice", "Thai fried rice", "Dumplings"]
  price=[5,7,8,5]
  findprice(items,price)



def findprice(items,price):
  print("---Find Price---")
  item=input("Enter Item:")
  for i in range(len(items)):
    if item==items[i]:
      print(price[i])
      break
    else:
      break
  print("There is no such item")
salestracker()

Solution

  • Here's another way to do that lookup, by letting Python do the search:

    def findprice(items,price):
      print("---Find Price---")
      item=input("Enter Item:")
      if item in items:
          print(price[items.index(item)])
      else:
          print("There is no such item")
    

    Even better, however, is to use the correct data structure to begin with. By storing in a dictionary, you carry both pieces of information in a single structure:

    def salestracker():
      print("---Sales Tracker---")
      print("---MENU---")
      print("""
      1. Find the price of an item
      2. Enter sales of an item
      3. Find total of the day
      
      """)
      
      menu = {
          "Chicken Wings": 5,
          "Jollof Rice": 7,
          "Thai fried rice": 8,
          "Dumplings": 5
      }
      findprice(menu)
    
    def findprice(menu):
      print("---Find Price---")
      item=input("Enter Item:")
      if item in menu:
          print(menu[item])
      else:
          print("There is no such item")
    salestracker()
    

    What that doesn't solve is issues of capitalization. Your cashiers will string you up by the thumbs trying to remember that both words in "Chicken Wings" are capitalized, but not in "Thai fried rice". If you take this further, consider storing the menu items in all lower case, and do item = item.lower().