Python Summing Array Elements
Define an integer array and calculate the sum of its elements.
Requirements:
Input : arr[] = {1, 2, 3}
Output : 6
Calculation: 1 + 2 + 3 = 6
Example
Define a function where arr is the array and n is the array length, which can be used as a spare parameter; it is not used here
def
_sum
(
arr
,
n
)
:
Calculate using the built-in sum function
return
(
sum
(
arr
)
)
Calling a function
arr
=
[
]
Array elements
arr
=
[
12
,
3
,
4
,
15
]
Calculate the length of the array elements
n
=
len
(
arr
)
ans
=
_sum
(
arr
,
n
)
Output result
(
'The sum of the array elements is'
,
ans
)
The output of the above example is:
数组元素之和为 34
Python3 Examples