Home > Software engineering >  Python program - returning every response from a loop instead of just the desired one
Python program - returning every response from a loop instead of just the desired one

Time:11-25

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()

CodePudding user response:

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().

CodePudding user response:

You should go with the answer by @Tim Roberts regarding the "best practice" part of your question, but to directly answer why your code is not working as expected, it's a simple placement error. What it should say is:

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:
      print("There is no such item") # [1]
      break
  # print("There is no such item") # Move this line up to [1]

CodePudding user response:

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

You can also use built-in list method - .index("")

CodePudding user response:

I think you should replace 'break' with 'return'. 'break' is used to exit a loop, but not the function. So, when it finds the item, it still prints "There is no such item". You can fix it by making the function return, which actually ends the execution of the function.

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

...
  • Related