...

/

Solution: Build a Sales Report Generator

Solution: Build a Sales Report Generator

Learn how to implement the coded solution of a sales report generator system using functional programming intersection.

Read sales data

First create a function named read_sales_data() that will assist us in reading the data written in a CSV file. The path of the file will be given as a parameter to the function.

Press + to interact
import csv
# Read Sales Data
def read_sales_data(file_path):
sales_data = []
with open(file_path, 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
sales_data.append(row)
return sales_data

Code explanation

  • Line 4–6: Passed the file_path as input and opened the file using open() method.
  • Line 7: Created a csv.DictReader object to read the contents of the file as a dictionary.
  • Line 8–9: Iterated each row in the CSV file and added it to the sales_data list.
  • Line 10: Finally, returned the sales_data list.

Calculate total sales

Now implement a calculate_total_sales() function to accept the sales_data as a parameter. This function calculates the total sales of each country and returns a dictionary containing the required data.

Press + to interact
import csv
# Read Sales Data
def read_sales_data(file_path):
sales_data = []
with open(file_path, 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
sales_data.append(row)
return sales_data
# Calculate Total Sales
def calculate_total_sales(sales_data):
total_sales = {}
for transaction in sales_data:
country = transaction['country']
quantity = int(transaction['quantity'])
price = float(transaction['price'])
sales = quantity * price
total_sales[country] = total_sales.get(country, 0) + sales
return total_sales

Code explanation

  • Line 13: Passed the sales_data as input, which is a list of dictionaries representing the sales data.
  • Line 15–18: Iterated over each transaction in the sales_data. For each transaction, it extracted the country, quantity, and price values.
  • Line 19: Calculated the sales by multiplying the
...