首页 文章

保存用户输入

提问于
浏览
0

我买卖产品,我想制作一个节省时间的程序 . 当我购买这些固定产品时,我想通过制作一个程序来询问我“x产品的数量”,然后是“产品y”等等来节省时间 . 最后,我希望它能够打印出我总共有多少产品,以及它们的美元 Value .

同样在问题之间我希望它以美元打印该产品的总额 . 例如,#INPUT“多少产品X”10 #OUTPUT:“你有10个产品X Value 100美元 . ”

然后在最后我希望python加起来x,y,z并打印“你有X总 Value 300美元的产品”

这是我到目前为止所提出的 .

product1 = 20
 product2 = 12
 product3 = 20
 product4 = 25
 product5 = 25
 product6 = 17
 product7 = 19
 product8 = 19
 product9 = 17
 product10 = 25
 product11 = 5
 product12 = 5
 product13 = 5
 product14 = 20
 product15 = 24

def timesaver():
    product1_amount = int(input("How many product1? "))
    print(f"You have {product1_amount} product1 and  {product1_amount * product1} Dollars worth\n\n")
    product1_total =  product1_amount 
    product1_dollars = product1_amount * product1
    print('\n\n')

我一遍又一遍地重复这一点,以完成工作,代码很糟糕,根本没有效率 . 任何帮助?

我也做了一些循环,询问这样的问题,将所有产品放入一个没有附加价格的清单中 .

但是如何将每个用户输入保存到不同的变量中,以便我可以对每个变量执行操作?

for index in products:
    question = int(input("How many " + str(index) + " ?"))

3 回答

  • 1

    您对函数的使用是一个良好的开端

    您可能需要考虑使用 dictionary . 它允许您按名称进行查找,它们是一个恒定的时间过程,这意味着无论您有多少产品,查找时间都是相同的 .

    这可以这样做:

    products = {'product1_name': 20, 'product2_name': 12, ..., 'productn_name': 300}
    

    考虑到这一点,您可以使用您的功能执行以下操作:

    def timesaver(product, amount):
        # Product is the name of the product you want
        val = products[product]
    
        # Amount is an integer value
        total = amount * val
    
        print("Total for product {0}: {1}".format(product, total))
    

    总使用可以使用您想要的 input 函数进行while循环:

    for product in products.keys():
        amt = int(input("How many of {}?  ".format(product)))
        timesaver(product, amt)
    
  • 2

    根据价格制作产品字典 . 然后遍历该字典以询问用户想要的特定产品的数量 . 使用该数据构建表示订单本身的第二个字典 .

    products = {
        "apple": 1.00,
        "pear": .70,
        "banana": .10,
        "kiwi": 1.50,
        "melon": 5.75,
        "pineapple": 12.0,
    }
    
    
    def get_order():
        order = {}
        for product, price in products.items():
            amount = int(input(f"How many {product} do you want at {price:.2f} each?"))
            order[product] = (price, amount)
        print("Your total is {:.2f}".format(sum(x*y for x, y in order.values())))
        return order
    
  • 1

    考虑将产品价格存储到数组中:

    products = [20, 12, 30, 25, 25, 17, 19, 19, 17, 25, 5, 5, 5, 20, 24]
    def timesaver() :
        productNumber = 1
        totals = []
        dollars = []
        for product in products :
            amount = int(intput("How many product{}? ".format(productNumber))
            print(f"You have {amount} product{productNumber} and {amount * product} Dollars worth\n\n")
            totals.append(amount)
            dollars.append(amount * product)
            print('\n\n')
         print(totals)
         print(dollars)
    

    现在您仍然保存了所有相同的值,

    例如: product1_total = totals[0]product2_total = totals[1] 等 .

相关问题