Page 363 - Computer Science Class 11 With Functions
P. 363
2. Shamitabh's teacher wants him to store the ages of all his friends in the form of a list and then perform the following
operations:
● Display the average age of all his friends
● Display the count of all his friends
● Display the most frequently occurring age value in the list
Help Shamitabh do his assignment using the Python functionality.
Ans. To develop the desired program to summarize the list of age, Shamitabh needs to take the following approach:
Approach:
a. Prompt the user to enter age one by one and append to an initially empty list.
b. If the user reponds by y or Y, continue, else stop and process data.
c. Use mean and mode methods of statistics module.
import statistics
'''
Objective: To read numbers representing ages and mean, count, and mode of all ages.
Input: a list of age
Output: count, mean, and the mode of list of age
'''
ageList = []
#Accept data from the user
more = 'y'
while more == 'y' or more == 'Y':
age = int(input("Enter the age : "))
ageList.append(age)
more = input("Do you wish to enter more (y/n): ")
#Process data entered by the user
print("Count of friends: ", len(ageList))
#round age to one place after decimal
print("Average age: ", round(statistics.mean(ageList), 1))
print("Most frequently occuring age: ", statistics.mode(ageList))
3. While Shamitabh's teacher appreciates him for being able to exploit the capabilities of Python, she wants him to develop
his own functions to carry out the desired operations. Help Shamitabh one more time.
Approach:
a. Prompt the user to enter age one by one and append to an initially empty list.
b. If the user reponds by y or Y, continue, else stop and process data.
c. Use meanList, countElements and modeList to find mean, count, and the mode of the elements of list.
'''
Objective: To compute the mean of the elements of a list
Input: a list of numbers
Output: mean of list
'''
def meanList(lst):
total = 0
count = 0
for element in lst:
total += element
count += 1
meanLst = total / count
Lists and Tuples 361

