-1
我是新來編碼並寫了一個腳本。我不明白爲什麼顯示的總數是錯誤的,每次運行程序時都會改變。我知道字典不會每次都按相同的順序存儲關鍵字和值,但我不明白爲什麼總數是錯誤的並且從不相同?有人可以幫忙嗎?我正在尋找一個解釋,以便從我的錯誤中學習。需要幫助理解python中的字典
stock = [["mp40", 4], ["crowbar", 3], ["machete", 4], ["5_person_tent", 3],
["gps", 10], ["duffle_bag", 3], ["first_aid_kit", 2], ["horse", 1],
["military_mre", 7], ["camping_stove", 1], ["hunting_vest", 2],
["jogging_pants", 3], ["timberlands", 2], ["gas_generator", 3],
["gasoline", 500], ["gas_can", 100], ["pontiac_grand_dam", 1]]
prices = [["mp40", 390], ["crowbar", 20], ["machete",40],["5_person_tent",250],
["gps", 97], ["duffle_bag",20], ["first_aid_kit",15], ["horse", 3000],
["military_mre",15],["camping_stove",15], ["hunting_vest", 60],
["jogging_pants", 60], ["timberlands", 150], ["gas_generator",180],
["gasoline", 3],["gas_can", 20], ["pontiac_grand_dam", 2000]]
def buy():
purchase =input("What item you want to buy?\n")
total = 0
for item in stock:
if purchase in stock.keys():
if stock[item] > 0:
amount =int(input("How many would you like to purchase?\n"))
total += (prices[item]*(amount))
stock[item] -=(amount)
print ('You owe'+' '+'$'+str(total))
input('press enter to continue \n')
return total
if stock[item]<1:
print ("we don't have any left\n")
if purchase!=item:
print ("We do not sell that.\n")
a=0
while a==0:
buy()
你沒有字典這裏。你有清單的列表。 – Andy
對於初學者,此代碼不會運行。 'stock'是一個列表,而不是一本字典。 – chepner
字典由'{'和'}'分隔,'['和']'表示列表 – PurityLake