Exercise
Array Summation Function
Objective
Develop a Python program to calculate the sum of the elements in an array. The main function should look like this:
def main():
example = [20, 10, 5, 2]
print("The sum of the example array is {}".format(sum_elements(example)))
You must define the function `sum_elements`, and it will be called from within the main function. As shown in the example, it must accept an array as a parameter and return the sum of its elements.
Example Python Exercise
Show Python Code
# Define the function sum_elements which calculates the sum of the elements in the array
def sum_elements(arr):
total = 0 # Initialize the total sum to 0
for num in arr: # Loop through each number in the array
total += num # Add the number to the total sum
return total # Return the total sum
# Main function to call sum_elements and display the result
def main():
example = [20, 10, 5, 2] # Define the example array
# Print the sum of the elements in the example array
print("The sum of the example array is {}".format(sum_elements(example))) # Call the function and format the result
# Call the main function to execute the program
main()
Output
The sum of the example array is 37
Share this Python Exercise