Calculating the sum of an array is a basic operation in programming. In Python, this can be achieved through various methods, from simple loops to built-in functions. Here, we’ll demonstrate different ways to compute the total sum of an array.
Using the Built-in sum Function
Python offers a built-in sum()
function that makes calculating the sum of an array (or list) very convenient. Here’s an example:
def calculate_array_sum(arr):
return sum(arr)
numbers = [1, 2, 3, 4, 5]
total_sum = calculate_array_sum(numbers)
print(f"数组的和是: {total_sum}")
Using a Loop
You can also manually compute the sum using a loop. Here’s an example:
def calculate_array_sum(arr):
total = 0
for num in arr:
total += num
return total
numbers = [1, 2, 3, 4, 5]
total_sum = calculate_array_sum(numbers)
print(f"数组的和是: {total_sum}")
Using the built-in sum
function is the easiest way to compute an array's sum, but knowing how to use loops is also useful, especially for more complex calculations.