You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Read input number asking for length of the list using input()
Initialise an empty list lst = [].
Read each number using a for loop.
In the for loop append each number to the list.
Now we use predefined function sum() to find the sum of all the elements in a list.
Print the result.
By Using Buil-in Function sum()
li= []
n=int(input("Enter the number of elements: "))
foriinrange(n):
elem=int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
Test Case-1
li= []
n=int(input("Enter the number of elements: "))
foriinrange(n):
elem=int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
Enter the number of elements: 4
Enter the elements: 30
Enter the elements: 30
Enter the elements: 30
Enter the elements: 30
The list: [30, 30, 30, 30]
The sum of the list = 120
Test Case-2
li= []
n=int(input("Enter the number of elements: "))
foriinrange(n):
elem=int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
Enter the number of elements: 10
Enter the elements: 4
Enter the elements: 5
Enter the elements: -10
Enter the elements: 20
Enter the elements: -50
Enter the elements: 30
Enter the elements: -9
Enter the elements: -2
Enter the elements: 0
Enter the elements: 7
The list: [4, 5, -10, 20, -50, 30, -9, -2, 0, 7]
The sum of the list = -5
Without Built-in Function Finding Sum
Source Code
numbers= []
n=int(input("Enter the elements: "))
foriinrange(0, n):
elem=int(input("Enter the elements: "))
numbers.append(elem)
deffindSum(numbers):
total=0forjinnumbers:
total+=jreturntotalif__name__=='__main__':
temp=findSum(numbers)
print("The created list: ",numbers)
print("The Sum = ",temp)
Test Case-1
numbers= []
n=int(input("Enter the elements: "))
foriinrange(0, n):
elem=int(input("Enter the elements: "))
numbers.append(elem)
deffindSum(numbers):
total=0forjinnumbers:
total+=jreturntotalif__name__=='__main__':
temp=findSum(numbers)
print("The created list: ",numbers)
print("The Sum = ",temp)
Enter the elements: 4
Enter the elements: 30
Enter the elements: 40
Enter the elements: 10
Enter the elements: 20
The created list: [30, 40, 10, 20]
The Sum = 100
numbers= []
n=int(input("Enter the elements: "))
foriinrange(0, n):
elem=int(input("Enter the elements: "))
numbers.append(elem)
deffindSum(numbers):
total=0forjinnumbers:
total+=jreturntotalif__name__=='__main__':
temp=findSum(numbers)
print("The created list: ",numbers)
print("The Sum = ",temp)