Mathew K Analytics

Lesson 32 · Python for Data Science

10 - Sales Data Analysis in Python: Step-by-Step Tutorial

Welcome! In this lesson, we will learn how to analyze sales data using Python. No experience needed we will start from the very basics and build up to a…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Introduction to Sales Data Analysis in Python#

Welcome! In this lesson, we will learn how to analyze sales data using Python.

No experience needed we will start from the very basics and build up to a mini-project.

Data analysis is an important skill for making smarter business decisions.

Let us get started!

What is Sales Data?#

Sales data usually shows who bought what, when, and for how much.

With Python, we can find trends, patterns, and helpful statistics.

# Let us start by making a simple list of sales amounts
sales = [20.0, 35.5, 12.0, 46.0, 28.75]
print(sales)  # This will show our sales data
[20.0, 35.5, 12.0, 46.0, 28.75]
# How many sales did we record?
num_sales = len(sales)
print(num_sales)
5
# What was the total amount of all sales?
total_sales = sum(sales)
print(total_sales)
142.25
# Let us find the average sale amount
average_sale = total_sales / num_sales
print(average_sale)
28.45

Storing More Complex Sales Data#

Lists only store numbers, but real sales data needs more details.

Python dictionaries let us keep track of things like customer names, items, and amounts.

# Creating a sale as a dictionary: it holds details in key-value pairs
sale1 = {'customer': 'Alice', 'item': 'Book', 'amount': 20.0}
print(sale1)
{'customer': 'Alice', 'item': 'Book', 'amount': 20.0}
# Let us create a list of dictionaries for multiple sales
sales_records = [
    {'customer': 'Alice', 'item': 'Book', 'amount': 20.0},
    {'customer': 'Bob', 'item': 'Pen', 'amount': 5.0},
    {'customer': 'Carol', 'item': 'Notebook', 'amount': 15.5},
    {'customer': 'Dan', 'item': 'Bag', 'amount': 45.0}
]
print(sales_records)
[{'customer': 'Alice', 'item': 'Book', 'amount': 20.0}, {'customer': 'Bob', 'item': 'Pen', 'amount': 5.0}, {'customer': 'Carol', 'item': 'Notebook', 'amount': 15.5}, {'customer': 'Dan', 'item': 'Bag', 'amount': 45.0}]
# Let us loop through sales and print each one nicely
for sale in sales_records:
    print(f"Customer: {sale['customer']} bought {sale['item']} for ${sale['amount']}")
    
Customer: Alice bought Book for $20.0
Customer: Bob bought Pen for $5.0
Customer: Carol bought Notebook for $15.5
Customer: Dan bought Bag for $45.0
# Calculate the total sales amount from all records
total = 0
for sale in sales_records:
    total += sale['amount']
print(total)
85.5
# What if a customer returns an item? Let us remove that sale by index.
returned_index = 1  # Suppose Bob returned the pen.
del sales_records[returned_index]
print(sales_records)
[{'customer': 'Alice', 'item': 'Book', 'amount': 20.0}, {'customer': 'Carol', 'item': 'Notebook', 'amount': 15.5}, {'customer': 'Dan', 'item': 'Bag', 'amount': 45.0}]
# Let us safely access a key even if it might not exist
if 'coupon' in sales_records[0]:
    print(sales_records[0]['coupon'])
else:
    print("No coupon used!")
    
No coupon used!
# Update a sale to record that a coupon was used
sales_records[0]['coupon'] = 'SUMMER20'
print(sales_records[0])
{'customer': 'Alice', 'item': 'Book', 'amount': 20.0, 'coupon': 'SUMMER20'}
# Let us filter the sales to find only those above $20
big_sales = []
for sale in sales_records:
    if sale['amount'] > 20:
        big_sales.append(sale)
print(big_sales)
[{'customer': 'Dan', 'item': 'Bag', 'amount': 45.0}]
# Using list comprehensions to find all customer names
customer_names = [sale['customer'] for sale in sales_records]
print(customer_names)
['Alice', 'Carol', 'Dan']
# Let us ask the user to add a new sale
customer = input('Customer name: ')
item = input('Item: ')
amount = float(input('Amount: '))
new_sale = {'customer': customer, 'item': item, 'amount': amount}
sales_records.append(new_sale)
print(sales_records)
[{'customer': 'Alice', 'item': 'Book', 'amount': 20.0, 'coupon': 'SUMMER20'}, {'customer': 'Carol', 'item': 'Notebook', 'amount': 15.5}, {'customer': 'Dan', 'item': 'Bag', 'amount': 45.0}, {'customer': 'Emma', 'item': 'Stapler', 'amount': 13.25}]
 
# Sort sales by amount, from highest to lowest
sorted_sales = sorted(sales_records, key=lambda x: x['amount'], reverse=True)
for sale in sorted_sales:
    print(f"{sale['customer']} spent ${sale['amount']} on a {sale['item']}")
    
Dan spent $45.0 on a Bag
Alice spent $20.0 on a Book
Carol spent $15.5 on a Notebook
Emma spent $13.25 on a Stapler
# Let us combine all sales amounts to get a daily summary
daily_total = sum([sale['amount'] for sale in sales_records])
print(f"Total sales for the day: ${daily_total}")
Total sales for the day: $93.75
# Let us make a small report showing customers and totals spent
totals = {}
for sale in sales_records:
    name = sale['customer']
    if name in totals:
        totals[name] += sale['amount']
    else:
        totals[name] = sale['amount']
for name, total in totals.items():
    print(f"{name}: ${total}")
    
Alice: $20.0
Carol: $15.5
Dan: $45.0
Emma: $13.25
# Let us handle the case where a customer might not be in the report
name = input('Enter a customer name to check total: ')
if name in totals:
    print(f"{name} spent ${totals[name]}")
else:
    print(f"No record for {name}")
    
Carol spent $15.5
 

Mini Project: Simple Sales Analysis Tool#

Now, let us pull everything together and make a simple tool for analyzing sales records.

We will use everything we learned so far!

# Mini Project, Part 1: Gather a few sales from the user
my_sales = []
for i in range(3):
    print(f"Enter info for sale {i+1}:")
    customer = input('Customer name: ')
    item = input('Item: ')
    amount = float(input('Amount: '))
    my_sales.append({'customer': customer, 'item': item, 'amount': amount})
print(my_sales)
Enter info for sale 1:
Enter info for sale 2:
Enter info for sale 3:
[{'customer': 'Gabby', 'item': 'Glasses', 'amount': 32.2}, {'customer': 'Ryan', 'item': 'Coffee', 'amount': 4.5}, {'customer': 'Helen', 'item': 'Book', 'amount': 11.0}]
 
# Mini Project, Part 2: Report stats and biggest sale
amounts = [sale['amount'] for sale in my_sales]
if amounts:
    print(f"Total sales: ${sum(amounts)}")
    print(f"Average sale: ${sum(amounts)/len(amounts):.2f}")
    max_sale = max(my_sales, key=lambda x: x['amount'])
    print(f"Biggest sale: {max_sale['customer']} bought a {max_sale['item']} for ${max_sale['amount']}")
else:
    print("No sales recorded.")
    
Total sales: $47.7
Average sale: $15.90
Biggest sale: Gabby bought a Glasses for $32.2
# Some tips for clean and safe data analysis!
# - Always check your data types.
# - Use try-except to handle unexpected input or errors.
# - Keep your code neat and comment important steps.
# - Test using both normal and weird data.

print("Tip: Small, clear changes make bugs easier to fix!")
Tip: Small, clear changes make bugs easier to fix!
# Common mistakes in sales data analysis
try:
    problem = float('twenty')  # This will not work!
except ValueError:
    print("Oops, be sure inputs are numbers!")
    
Oops, be sure inputs are numbers!

Wrap-Up & Next Steps#

Awesome job learning the basics of sales data analysis in Python!

You can now store, update, search, sort, and analyze basic business data.

Keep trying new examples to make these skills automatic.

Thank You & YouTube Call to Action#

If you learned something new, please like this video!

Comment your questions, subscribe for more, and share this lesson with friends.

Keep practicing and see you in the next lesson!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.