我有以下 Python 程式,并希望該程式簡單地回傳串列“專案”中相應專案的價格。相反,如您所見,它無法正常作業,要么中斷,要么回傳“沒有這樣的專案”,然后回傳數字。我嘗試了各種方法,但無法獲得正確的輸出順序。
https://trinket.io/python/77909a6574
期望的輸出:
User enters: Chicken Wings
Output: 5
User enters: Jollof Rice
Output: 7
等等。
任何人都可以建議修復以及在 for 回圈中使用 if 陳述句并在正確的時間中斷的最佳實踐。
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()
uj5u.com熱心網友回復:
這是通過讓 Python 進行搜索來進行查找的另一種方法:
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")
然而,更好的是首先使用正確的資料結構。通過存盤在字典中,您可以在一個結構中攜帶兩條資訊:
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()
不能解決的是資本化問題。您的收銀員會用拇指把您串起來,試圖記住“Chicken Wings”中的兩個單詞都是大寫的,但在“Thai Fried Rice”中卻不是。如果您更進一步,請考慮以全部小寫形式存盤選單項,然后執行item = item.lower()。
uj5u.com熱心網友回復:
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")
您還可以使用內置串列方法 - .index("")
uj5u.com熱心網友回復:
我認為您應該用“回傳”替換“中斷”。'break' 用于退出回圈,但不是函式。因此,當它找到該專案時,它仍然列印“沒有這樣的專案”。您可以通過使函式回傳來修復它,這實際上結束了函式的執行。
...
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")
...
uj5u.com熱心網友回復:
您應該使用Tim Roberts關于問題的“最佳實踐”部分的答案,但要直接回答為什么您的代碼沒有按預期作業,這是一個簡單的放置錯誤。它應該說的是:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367555.html
