首页 文章

Python:使用for循环时如何存储多个用户输入?

提问于
浏览
1

我试图从我们的课堂作业中重新创造一个问题:

编写一个可以处理购物活动的程序 . 首先,它要求购买的商品数量,然后询问每个商品的价格和税率 . 然后打印总成本 .

例:
你买了多少件:2

对于第1项
输入价格:10
输入税率:0

对于第2项
输入价格:20
输入税率:8
您的总价为31.6


我不知道如何计算大于1的项目 . 即我的代码适用于1项 .

items = int(input("How many items did you buy? "))

for i in range(1, items+1, 1):
    print("For item ",i)
    price = float(input("Enter the price: "))
    tax_rate = float(input("Enter the tax rate: "))
    total = price + price*(tax_rate/100)

print("Your total price is", total)

我需要以某种方式在每次迭代后保存总计并将它们全部添加 . 我很难过 .

注意:这是对python课程的介绍,也是我的第一门编程课程 . 到目前为止,我们只学习了循环 .

1 回答

  • 1

    您需要有一个初始化计数器才能获得总计 .

    items = int(input("How many items did you buy? "))
    total = 0
    
    for i in range(1, items+1, 1):
        print("For item ",i)
        price = float(input("Enter the price: "))
        tax_rate = float(input("Enter the tax rate: "))
        total += price + price*(tax_rate/100)
    
    print("Your total price is", total)
    

相关问题