In this section you will find Functions Exercises in Python.
Try these exercises on your own, and the checkout the solutions.
Learn about functions in here.
Exercise 1: From given list
gadgets = [“Mobile”, “Laptop”, 100, “Camera”, 310.28,
“Speakers”, 27.00, “Television”, 1000, “Laptop Case”, “Camera Lens”]
a) Calculate the total price of the all the gadgets.
b) Calculate the average of all the gadgets.
Solution:
gadgets = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00, "Television", 1000, "Laptop Case", "Camera Lens"] def number_list(item_list): prices = [] for item in item_list: if isinstance(item, int) or isinstance(item, float): prices.append(item) return prices price_list = number_list(gadgets) print(price_list) #function get total prices and item count def calculate_toal_count(prices): total = sum(map(float,prices)) count = len(prices) return total, count #function to calculate average def average(total, count): return total/count total_value, num_items = calculate_toal_count(price_list) average_value = average(total_value, num_items) print("total :{0} average: {1}".format(total_value,average_value))