gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:08 26 4
gpt4 key购买 nike

我正在尝试重现类作业中的一个问题:

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

示例:
您购买了多少件商品: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入门类(class),也是我的第一门编程类(class)。到目前为止我们只学习了 for 循环。

最佳答案

您需要有一个初始化的计数器才能获得运行总计。

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)

关于Python:使用for循环时如何存储多个用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com