我是编码和编写脚本的新手。我无法理解为什么显示的总数是错误的,并且每次运行程序时都会更改。我知道字典不会每次都以相同的顺序存储密钥和值,但我不明白为什么总数是错误的并且从不相同?有人可以帮忙吗?我正在寻找解释,以便从错误中吸取教训。
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()
答案 0 :(得分:1)
您需要制作stock
和prices
词典,而不是列表。幸运的是,您的当前数据使这很容易,因为dict
可以将键值对列表作为参数。也就是说,
stock = [...] # current definition
stock = dict(stock)
prices = [ ... ] # current definition
prices = dict(prices)
“手动”定义字典看起来像
stock = {"mp40":4,
"crowbar":3,
"machete":4, } # etc