我刚刚开始学习Python,我真的很感激这方面的一些建议。
当我尝试在“total_price”中保存最后一次总计时列表,它没有保存。 我做错了什么?
此外,有没有更好的方法来写这个? 谢谢
price_list = {'gold': 10,
'red': 20,
'brown': 30
}
vol_list = {'gold': 0.1,
'red': 0.2,
'brown': 0.3
}
cl_list = {'gold': 100,
'red': 200,
'brown': 300
}
while True:
print("What do you want to buy?")
choice = input("Choices: gold, red or brown > ")
amount = int(input("How many do you want? >"))
price = price_list[choice] * amount
vol = (cl_list[choice] * amount) * vol_list[choice]
total_price = []
total_vol = []
total_price.append(price)
total_vol.append(vol)
print_price = sum(total_price[:])
print_vol = sum(total_vol[:])
print("-" * 10)
print("Your total is now: ", print_price)
print("Your total vol is now: ", print_vol)
print("-" * 10)
cont = input("Do you want to continue shopping [Y/n]?> ")
if cont == "n" or cont == "no":
print("#" * 10)
print("#" * 10)
print("Your total is: ", print_price)
print("Your total vol is: ", print_vol)
print("#" * 10)
print("#" * 10)
break
答案 0 :(得分:3)
您正在while循环中初始化数组,因此在每次新迭代时,旧的total_price
都会被覆盖。
在循环
之前初始化数组total_price = []
total_vol = []
while True:
...