在Python中,将列表内的数字加起来可以通过以下两种常见方法实现:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("列表中的数字相加结果为:", total)
2. 使用内建函数`sum()`:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("列表中的数字相加结果为:", total)
两种方法都可以得到正确的累加结果。您可以根据自己的需求选择合适的方法