查找小计的总数

时间:2019-03-04 01:54:40

标签: python python-3.x

我正在运行一个程序,在该程序中,提示用户在“快速”结帐行中输入项目数。然后,它向用户请求商品的价格和数量,并打印小计。一旦用户输入的所有项目都已计入程序,就会显示所有小计的总计。我已经到了最后一部分,我需要对用户的小计进行累加。任何帮助将不胜感激,

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()

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您的代码有很多错误。

  1. 您不要在函数名称和args之间放置空格。这会犯很多错误。

  2. 正确使用格式的方式是:'string {0}'。format(variable_name)

  3. 为什么要将整个脚本放入“ main”函数中?这不是C。但是如果您对此感到满意,那么可以。

但是,回答问题,您可以使“小计”功能接收产品列表,并使其返回小计的列表,并使其余的数学部分成为“主要”功能。

相关问题