Python 查找小计的总数

Python 查找小计的总数,python,python-3.x,Python,Python 3.x,我正在运行一个程序,它会提示用户在“快速”结账行输入项目数。然后,它向用户请求商品的价格和数量,并打印小计。一旦用户输入的所有项目均已入账,程序将显示所有小计的总数。我已经到了最后一部分,我需要把用户的小计加起来。任何帮助都将不胜感激 def main(): total = 0 while True: item = int(input("How many different items are you buying? ")) if item in

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

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

您的代码有大量错误

  • 函数名和参数之间没有空格。它犯了很多错误

  • 使用格式的正确方法是:“字符串{0}”。格式(变量名称)

  • 为什么要将整个脚本放入“main”函数中?这不是C,但如果你觉得舒服的话,好吧

  • 但是回答这个问题,您可以让“subtotal”函数接收产品列表,让它返回一个小计列表,并在“main”函数中生成数学部分的其余部分。

    函数通过循环每次重新分配小计()函数,丢弃以前的值,因此,它最终只返回最后一项的总数

    请尝试以下方法:

    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
    

    好的,谢谢你的反馈。每个作业的小计数学部分必须在“小计”函数中。我玩列表已经有一段时间了,似乎无法将它从列表转换为int。请澄清最后一点。@Mattr42哦!您可以在“列表中的i”函数中使用“list.append(subtotal(number))!还是我误会了?