【问题标题】:How can I minimize my code when I use a while loop?当我使用 while 循环时,如何最小化我的代码?
【发布时间】:2021-08-29 07:31:15
【问题描述】:

我的任务是创建一个超市产品列表,我试图将代表产品 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])

【问题讨论】:

  • 价格[selection-1]

标签: python python-3.x while-loop


【解决方案1】:

无需检查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])

这显然大大减少了行数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2022-12-12
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多