CBSE Class 12 Computer Science Question 53 of 56

Functions — Question 53

Back to all questions
53
Question

Question 46

Write a program using user-defined function to calculate and display average of all the elements in a user-defined tuple containing numbers.

Solution
def calculate_average(num):
    total = 0
    for element in num:
        total += element
    average = total / len(num)
    return average

n = eval(input("Enter the tuple: "))
average = calculate_average(n)
print("The average of the elements in the tuple is:", average)
Output
Enter the tuple: (2, 4, 6, 8, 10)
The average of the elements in the tuple is: 6.0
Answer

def
calculate_average
(
num
):
total
=
0
for
element
in
num
:
total
+=
element
average
=
total
/
len
(
num
)
return
average
n
=
eval
(
input
(
"Enter the tuple: "
))
average
=
calculate_average
(
n
)
print
(
"The average of the elements in the tuple is:"
,
average
)
Output
Enter the tuple: (2, 4, 6, 8, 10)
The average of the elements in the tuple is: 6.0