Python 名称';总计';尝试使用for循环求和时未定义

Python 名称';总计';尝试使用for循环求和时未定义,python,python-3.x,for-loop,Python,Python 3.x,For Loop,我试图使用for循环而不是sum函数对这个列表求和,但它一直告诉我名称没有定义 monthly_sales = [500, 600, 600, 500, 200, 700, 500, 100, 100, 600] for sales_value in monthly_sales: total = total + sales_value print("Total in annual sales is $", total) 我希望输出中会有一行写着“年销售总额为4400美元”。如评论中所

我试图使用for循环而不是sum函数对这个列表求和,但它一直告诉我名称没有定义

monthly_sales = [500, 600, 600, 500, 200, 700, 500, 100, 100, 600]
for sales_value in monthly_sales:
    total = total + sales_value

print("Total in annual sales is $", total)

我希望输出中会有一行写着“年销售总额为4400美元”。

如评论中所述,在循环中引用变量之前,只需初始化变量:

total = 0
我们还可以编写一个更具Python风格的解决方案,如下所示:

total = sum(monthly_sales)

您必须先声明total=0,然后才能更改total=total+值:

total += value


在执行total+=x之前,需要实例化total;t声明(初始化)总计,但您正在使用它。在for循环之前添加
total=0
。或者一行中的所有内容:
print(“年销售总额为$”,sum(月销售))
。当您第一次遇到
Total=Total+sales\u value
时,您希望
Total
是什么?如果您之前没有定义Total,python不知道使用什么作为第一个值(即第一次循环时)谢谢我通常使用sum函数,但需要测试另一种方法。
monthly_sales = [500, 600, 600, 500, 200, 700, 500, 100, 100, 600]

total = 0
for sales_value in monthly_sales:
    total += sales_value

print("Total in annual sales is $", total)