Discover How to Find the Sum of an Array in Python with Simple and Efficient Code. Learn How to Use Python Functions to Sum an Array and Prompt Users to Input Array Elements. Get Started with Our Step-by-Step Guide to Python Arrays and Start Computing Sums in Minutes



  • This code is a Python program that finds the sum of an array by prompting the user to enter the number of elements they want to include in the array, and then prompting the user to enter each element one by one. 
  • The program uses a function called sum_array() that takes an array as its argument and returns the sum of all its elements. The program then calls this function on the user-defined array to get the sum, and finally, it prints out the sum of the array. This program is a simple and effective way to find the sum of an array in Python, and it is easily customizable for different array sizes and types.

def sum_array(arr):
    """Returns the sum of all elements in an array."""
    total = 0
    for i in arr:
        total += i
    return total

# Prompt user to enter the number of elements
n = int(input("Enter the total number of elements: "))

# Create an empty list to store the elements
arr = []

# Prompt user to enter each element and add it to the list
for i in range(n):
    element = int(input("Enter element {}: ".format(i+1)))
    arr.append(element)

# Call the sum_array() function to get the sum of the array
sum = sum_array(arr)

# Print the result
print("Sum of the array is", sum)




Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.