Python Calculate Sum of Array Elements
Define an integer array and calculate the sum of its elements.
Implementation requirements:
Input: arr[] = {1, 2, 3}
Output: 6
Calculation: 1 + 2 + 3 = 6
Example
# Define a function, arr is the array, n is the array length, can be used as a spare parameter, not used here
def _sum(arr,n):
# Use the built-in sum function to calculate
return(sum(arr))
# Call the function
arr=[]
# Array elements
arr = [12, 3, 4, 15]
# Calculate the length of the array elements
n = len(arr)
ans = _sum(arr,n)
# Output the result
print ('The sum of array elements is',ans)
def _sum(arr,n):
# Use the built-in sum function to calculate
return(sum(arr))
# Call the function
arr=[]
# Array elements
arr = [12, 3, 4, 15]
# Calculate the length of the array elements
n = len(arr)
ans = _sum(arr,n)
# Output the result
print ('The sum of array elements is',ans)
The above example outputs the following:
数组元素之和为 34Other extensions
Python3 Examples