我正在运行一个程序,其中提示用户在“快速”结帐行中输入项目数。然后,它向用户请求商品的价格和数量,并打印小计。一旦用户输入的所有项目都已计入程序,就会显示所有小计的总计。我已经到了最后一部分,我需要对用户的小计进行累加。任何帮助,将不胜感激,
def main():
total = 0
while True:
item = int(input("How many different items are you buying? "))
if item in range (1, 10):
total += subtotal(item)
print("Total of this order $", format (total, ',.2f'), sep='')
break
else:
print("***Invalid number of items, please use a regular checkout line***")
break
def subtotal(item):
total = 0
for item in range(item):
unit_price = float(input("Enter the unit price of the item "))
quantity = int(input("Enter the item quantity "))
subtotal = unit_price * quantity
print("Subtotal for this item: $", format (subtotal, ',.2f'), sep='')
return subtotal
main()
最佳答案
subtotal()
函数每次通过循环都会重新分配小计,丢弃先前的值,因此最终只返回最后一项的总计。
尝试以下方法:
def subtotal(item):
total = 0
for item in range(item):
unit_price = float(input("Enter the unit price of the item "))
quantity = int(input("Enter the item quantity "))
subtotal = unit_price * quantity
print("Subtotal for this item: $", format (subtotal, ',.2f'), sep='')
total += subtotal
return total
关于python - 查找小计的总数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54975667/