我有一个任务是创建一个超市产品列表,我试图抛出价格元素,这些元素代表产品1到10的价格。我试图做字典和使用while循环,但它不起作用。有什么关于如何改进我的代码并使其更紧凑的帮助吗?
print("""Supermarket
===========""")
prices = [10,14,22,33,44,13,22,55,66,77]
totalsum = []
while True:
selection = int(input("Please select product (1-10) 0 to Quit:"))
if selection == 0:
print("Total: ", sum(totalsum))
payment = int(input("Payment: "))
var1 = payment - sum(totalsum)
print("Change: ", var1)
break
elif selection == 1:
print("Product: ", selection, " Price:", prices[0])
totalsum.append(prices[0])
elif selection == 2:
print("Product: ", selection, " Price:", prices[1])
totalsum.append(prices[1])
elif selection == 3:
print("Product: ", selection, " Price:", prices[2])
totalsum.append(prices[2])
elif selection == 4:
print("Product: ", selection, " Price:", prices[3])
totalsum.append(prices[3])
elif selection == 5:
print("Product: ", selection, " Price:", prices[4])
totalsum.append(prices[4])
elif selection == 6:
print("Product: ", selection, " Price:", prices[5])
totalsum.append(prices[5])
elif selection == 7:
print("Product: ", selection, " Price:", prices[6])
totalsum.append(prices[6])
elif selection == 8:
print("Product: ", selection, " Price:", prices[7])
totalsum.append(prices[7])
elif selection == 9:
print("Product: ", selection, " Price:", prices[8])
totalsum.append(prices[8])
elif selection == 10:
print("Product: ", selection, " Price:", prices[9])
totalsum.append(prices[9])发布于 2021-06-13 03:59:49
不需要检查selection的值。您可以简单地使用如下所示的选择对prices进行索引。
print("""Supermarket
===========""")
prices = [10,14,22,33,44,13,22,55,66,77]
totalsum = []
while True:
selection = int(input("Please select product (1-10) 0 to Quit:"))
if selection == 0:
print("Total: ", sum(totalsum))
payment = int(input("Payment: "))
var1 = payment - sum(totalsum)
print("Change: ", var1)
break
print("Product: ", selection, " Price:", prices[selection-1])
totalsum.append(prices[selection-1])这显然大大减少了行的数量。
https://stackoverflow.com/questions/67952523
复制相似问题