首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在使用while循环时,如何最小化我的代码?

在使用while循环时,如何最小化我的代码?
EN

Stack Overflow用户
提问于 2021-06-13 03:52:39
回答 1查看 39关注 0票数 0

我有一个任务是创建一个超市产品列表,我试图抛出价格元素,这些元素代表产品1到10的价格。我试图做字典和使用while循环,但它不起作用。有什么关于如何改进我的代码并使其更紧凑的帮助吗?

代码语言:javascript
运行
复制
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])
EN

Stack Overflow用户

回答已采纳

发布于 2021-06-13 03:59:49

不需要检查selection的值。您可以简单地使用如下所示的选择对prices进行索引。

代码语言:javascript
运行
复制
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])

这显然大大减少了行的数量。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67952523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档