Write a program to input ‘n’ numbers and store it in a tuple and find the sum of its elements.
Answers
Required Answer:-
Question:
- Write a program to input 'n' numbers and store it in a tuple and find the sum of its elements.
Solution:
Remember that,
- Tuple is a dynamic array.
- It is unchangeable.
So, to append elements in a tuple, we need to convert the tuple into a list first. We will then take the numbers as input, add inside the list and after that we will convert list to tuple.
Syntax to convert:
a = () [It is tuple]
l = list(a) [l is the list]
l = [ ]
a = tuple(l)
So, here comes the program.
a=()
l=list(a)
s=0
n=int(input("Enter n - "))
for i in range(0,n):
x=int(input("Enter: "))
l.append(x)
s+=x
a=tuple(l)
print("The tuple is...",a)
print("Sum of all elements is: ",s)
You can also try this approach. sum() function can be used to find the sum of elements in an array.
a=()
l=list(a)
s=0
n=int(input("Enter n - "))
for i in range(0,n):
x=int(input("Enter: "))
l.append(x)
s+=x
a=tuple(l)
print("The tuple is...",a)
print("Sum of all elements is: ",sum(a))
Take n (number of inputs to be taken) as input. Enter n elements and then store it in a list. Convert list to tuple. Add all elements. Display it.
Output is attached.



