Python

Python Essentials for Data Engineers, Part 1

Learn Python variables, strings, numbers, lists, dictionaries, conditions and loops on real sales records, and calculate the revenue of valid transactions without pandas.

By Javier GuerreroPublished 12 min readBeginner

A data pipeline is, at heart, a loop: take one record, decide whether it is good, do something with it, move on to the next. Before reaching for pandas or Spark, it pays to be able to write that loop yourself in plain Python, because every tool you will use later does the same thing underneath, and because you will often need to debug it.

This lesson teaches the Python you need for that, using eight real sales records. By the end you will calculate the revenue of the valid transactions with nothing but the language itself. It is the second Python lesson of Stage 2 of the Become a Data Engineer roadmap.

What you will learn

  • Store values in variables and recognise Python’s basic types: str, int, float, bool and None
  • Work with strings and numbers, and format results for reading
  • Group data in lists, tuples and dictionaries
  • Write conditions with comparisons, and, or, not, and if / elif / else
  • Loop over a list of transaction records
  • Detect missing values and skip invalid records
  • Filter and aggregate records to produce a total
  • Read and fix the error messages beginners see most

Before you start

  • Prerequisites: Set Up Python for Data Engineering. You need the sales-pipeline folder with an active virtual environment.
  • Estimated time: 60–90 minutes, including the exercises.
  • Packages: none. Everything here is built into Python.

How to run the examples

In VS Code, create a file named essentials.py in sales-pipeline. Type each example below the previous one, save, and run the whole file from the terminal:

python essentials.py

Later examples reuse variables created by earlier ones, so keep them in order. The output block under each example shows the lines that example adds. Typing the code yourself, rather than pasting it, is slower but helps you remember it.

The sample data

The examples use the first eight rows of sales_transactions.csv, the file you saved in Lesson 1. In this lesson the rows are written directly in Python; in Part 2 you will read the file itself.

transaction_id store product quantity unit_price
T1001 Lisbon Notebook 3 4.50
T1002 Lisbon Desk Lamp 1 24.90
T1003 Porto Backpack 2 39.00
T1004 Porto Notebook 5 4.50
T1005 Lisbon Water Bottle 0 12.00
T1006 Faro Desk Lamp 2 24.90
T1007 Faro (missing) 1 15.00
T1008 Porto Backpack -1 39.00

Three rows are deliberately wrong: a sale of zero units, a sale with no product and a negative quantity. A real pipeline must notice them instead of adding them to the revenue.

Variables and basic types

A variable is a name that refers to a value. You create one with =. Python works out the type from the value, and type() tells you what it decided:

PythonVariables and their types9 lines
Python
transaction_id = "T1001"
quantity = 3
unit_price = 4.50
is_paid = True

print(type(transaction_id))
print(type(quantity))
print(type(unit_price))
print(type(is_paid))
Python9 linesRead-only example cell. Nothing on this page runs code.
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
  • str (string) is text, written in quotes.
  • int (integer) is a whole number.
  • float is a number with a decimal point.
  • bool (Boolean) is either True or False, with a capital letter.

There is one more value you will meet constantly: None, Python’s way of saying “no value here”. It is how this lesson represents the missing product.

Names are case-sensitive (Quantity and quantity are different variables). By convention, Python variable names use lowercase words separated by underscores, like the column names in the CSV.

Strings and numbers

Arithmetic works as you would expect. To show numbers in a sentence, an f-string (a string with f before the quote) inserts values written between braces; :.2f formats a number with exactly two decimals:

PythonCalculate and format a line total11 lines
Python
line_total = quantity * unit_price
print(line_total)
print(f"{transaction_id}: {quantity} x {unit_price:.2f} = {line_total:.2f}")

product = "  desk lamp "
print(product.strip().title())

quantity_text = "3"
print(int(quantity_text) + 1)
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
Python11 linesRead-only example cell. Nothing on this page runs code.
13.5
T1001: 3 x 4.50 = 13.50
Desk Lamp
4
0.30000000000000004
0.3
  • strip() removes spaces at both ends and title() capitalises each word. Cleaning text like this is everyday work, because source systems rarely agree on spacing and case.
  • Values read from files arrive as text. "3" is a string, not a number: int("3") converts it to an integer and float("4.50") to a float. Part 2 relies on this heavily.
  • 0.1 + 0.2 is not exactly 0.3, because floats are stored in binary. Round or format money for display, and compare totals after rounding. (Production financial systems often use the decimal module instead; floats are fine for learning.)

Lists, tuples and dictionaries

A list holds several values in order, inside square brackets. Positions start at 0. A tuple is like a list that cannot change, written with parentheses; it is handy for a fixed pair such as a date range. A dictionary stores values under names, called keys, which makes it a natural fit for one record:

PythonLists, tuples and dictionaries15 lines
Python
stores = ["Lisbon", "Porto", "Faro"]
print(stores[0])
print(len(stores))
stores.append("Braga")
print(stores)

sales_week = ("2026-03-02", "2026-03-08")
first_day, last_day = sales_week
print(first_day, "to", last_day)

sale = {"transaction_id": "T1001", "product": "Notebook", "quantity": 3, "unit_price": 4.50}
print(sale["product"])
sale["store"] = "Lisbon"
print(sale)
print(sale.get("discount"))
Python15 linesRead-only example cell. Nothing on this page runs code.
Lisbon
3
['Lisbon', 'Porto', 'Faro', 'Braga']
2026-03-02 to 2026-03-08
Notebook
{'transaction_id': 'T1001', 'product': 'Notebook', 'quantity': 3, 'unit_price': 4.5, 'store': 'Lisbon'}
None
  • len() counts items and append() adds one to the end of a list.
  • first_day, last_day = sales_week unpacks the tuple into two variables.
  • sale["product"] reads a key; assigning to a new key adds it.
  • sale.get("discount") returns None when the key does not exist, where sale["discount"] would stop the program with an error. Use get() when a field may legitimately be absent.

A list of dictionaries, one dictionary per row, is the plain-Python version of a table. You will use it in a moment.

Booleans and comparisons

Comparisons produce True or False: == (equal), != (not equal), >, <, >= and <=. Note that = assigns a value, while == compares two values. You combine conditions with and, or and not:

PythonComparisons and Boolean logic6 lines
Python
quantity = 0
print(quantity > 0)
print(quantity == 0)
print(quantity > 0 and unit_price > 0)
print(quantity > 0 or unit_price > 0)
print(not is_paid)
Python6 linesRead-only example cell. Nothing on this page runs code.
False
True
False
True
False

and is True only when both sides are true; or is True when at least one side is. That is exactly how validation rules combine: a sale is valid when the quantity is positive and the price is positive.

Decisions with if, elif and else

if runs a block of code only when its condition is true. elif (“else if”) checks another condition, and else catches everything left. The block belongs to the condition because it is indented by four spaces; the colon at the end of the line is required:

PythonClassify quantities7 lines
Python
for quantity in [3, 0, -1]:
    if quantity > 0:
        print(quantity, "-> sale")
    elif quantity == 0:
        print(quantity, "-> empty line, reject")
    else:
        print(quantity, "-> negative, reject")
Python7 linesRead-only example cell. Nothing on this page runs code.
3 -> sale
0 -> empty line, reject
-1 -> negative, reject

Python checks the conditions from top to bottom and runs only the first block whose condition is true. The for line, which repeats the decision for three test values, is the subject of the next section.

Loop over transaction records

A for loop runs its indented block once for each item in a list, putting the current item in the loop variable. Here is the sample data as a list of dictionaries. The missing product is None:

PythonThe eight records and a first loop14 lines
Python
transactions = [
    {"transaction_id": "T1001", "store": "Lisbon", "product": "Notebook", "quantity": 3, "unit_price": 4.50},
    {"transaction_id": "T1002", "store": "Lisbon", "product": "Desk Lamp", "quantity": 1, "unit_price": 24.90},
    {"transaction_id": "T1003", "store": "Porto", "product": "Backpack", "quantity": 2, "unit_price": 39.00},
    {"transaction_id": "T1004", "store": "Porto", "product": "Notebook", "quantity": 5, "unit_price": 4.50},
    {"transaction_id": "T1005", "store": "Lisbon", "product": "Water Bottle", "quantity": 0, "unit_price": 12.00},
    {"transaction_id": "T1006", "store": "Faro", "product": "Desk Lamp", "quantity": 2, "unit_price": 24.90},
    {"transaction_id": "T1007", "store": "Faro", "product": None, "quantity": 1, "unit_price": 15.00},
    {"transaction_id": "T1008", "store": "Porto", "product": "Backpack", "quantity": -1, "unit_price": 39.00},
]

print(len(transactions))
for sale in transactions:
    print(sale["transaction_id"], sale["product"], sale["quantity"])
Python14 linesRead-only example cell. Nothing on this page runs code.
8
T1001 Notebook 3
T1002 Desk Lamp 1
T1003 Backpack 2
T1004 Notebook 5
T1005 Water Bottle 0
T1006 Desk Lamp 2
T1007 None 1
T1008 Backpack -1

The name sale is your choice; pick one that says what each item is. Splitting a long list over several lines, one record per line, is allowed because the brackets are still open; it makes the data far easier to read.

Handle missing values

To test for a missing value, use is None (or is not None), not == None. Counting is a pattern you will reuse everywhere: start a counter at zero and add one each time a condition is met:

PythonFind and count missing products9 lines
Python
for sale in transactions:
    if sale["product"] is None:
        print(sale["transaction_id"], "has no product")

missing = 0
for sale in transactions:
    if sale["product"] is None:
        missing = missing + 1
print("Missing products:", missing)
Python9 linesRead-only example cell. Nothing on this page runs code.
T1007 has no product
Missing products: 1

Missing values cause the most confusing errors in data code. Comparing None with a number, for example None > 0, raises a TypeError, so always check for missing values before you calculate or compare. In files, “missing” often arrives as an empty string "" rather than None; Part 2 handles both.

Filter and aggregate

Filtering keeps the records that pass your rules. Aggregating combines many records into one number, such as a sum or a count. continue skips to the next record immediately, which keeps each rule on its own readable line:

PythonKeep valid sales, then sum units14 lines
Python
valid_sales = []
for sale in transactions:
    if sale["product"] is None:
        continue
    if sale["quantity"] <= 0:
        continue
    valid_sales.append(sale)

print("Valid:", len(valid_sales), "of", len(transactions))

total_units = 0
for sale in valid_sales:
    total_units += sale["quantity"]
print("Units sold:", total_units)
Python14 linesRead-only example cell. Nothing on this page runs code.
Valid: 5 of 8
Units sold: 13

total_units += sale["quantity"] is shorthand for total_units = total_units + sale["quantity"]. Notice the order of the two checks: the missing product is tested first, so a record with no product never reaches the quantity rule.

Put it together: revenue of valid transactions

Now the goal of the lesson. For each record, decide whether it is valid, add its line total to the revenue if it is, and remember its ID if it is not:

  1. Next record
  2. Check the rulesproduct present, quantity and price above zero
    • valid
      Add to revenue
    • invalid
      Remember the ID
One pass over the records
PythonTotal revenue of valid transactions15 lines
Python
total_revenue = 0.0
valid_count = 0
rejected_ids = []

for sale in transactions:
    is_valid = sale["product"] is not None and sale["quantity"] > 0 and sale["unit_price"] > 0
    if is_valid:
        total_revenue += sale["quantity"] * sale["unit_price"]
        valid_count += 1
    else:
        rejected_ids.append(sale["transaction_id"])

print(f"Valid transactions: {valid_count}")
print(f"Rejected: {rejected_ids}")
print(f"Total revenue: {total_revenue:.2f}")
Python15 linesRead-only example cell. Nothing on this page runs code.
Valid transactions: 5
Rejected: ['T1005', 'T1007', 'T1008']
Total revenue: 188.70

The five valid sales are 13.50 + 24.90 + 78.00 + 22.50 + 49.80 = 188.70. The condition relies on and stopping at the first false part: for T1007, sale["product"] is not None is already false, so Python never evaluates the rest. Rejected IDs are kept rather than silently dropped, because “what did we reject, and why?” is the first question anyone asks about a pipeline’s numbers.

Exercises

Add each solution to essentials.py, below the code above, and compare your output with the expected result. Solutions follow the knowledge check.

  1. Revenue per store. Calculate the revenue of valid sales for each store, using a dictionary whose keys are store names. Expected output:

    Lisbon: 38.40
    Porto: 100.50
    Faro: 49.80
  2. Largest valid sale. Find the valid transaction with the largest line total. Expected output: T1003 78.00.

  3. Notebooks sold. Count the units of Notebook in valid sales. Expected output: Notebooks sold: 8.

Debugging beginner mistakes

Python’s error messages look alarming, but the last line names the problem and the lines above it point to where it happened. These are the ones you are most likely to meet in this lesson, with the exact message:

Mistake Message (last line) Fix
Misspelled key: sale["prodcut"] KeyError: 'prodcut' Check the spelling, or use sale.get("product")
Text times a decimal: "3" * 4.50 TypeError: can't multiply sequence by non-int of type 'float' Convert first: int("3") * 4.50
Text plus a number: "3" + 1 TypeError: can only concatenate str (not "int") to str Convert with int(), or build text with an f-string
Comparing a missing value: None > 0 TypeError: '>' not supported between instances of 'NoneType' and 'int' Test is None before comparing
= instead of == in a condition SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? Use == to compare
Forgot to indent a loop body IndentationError: expected an indented block after 'for' statement on line 1 Indent the block by four spaces

Two habits make debugging faster. Add print() lines to see what a variable actually contains, for example print(sale) inside a loop. And change one thing at a time, then run again.

Knowledge check

  1. What is the type of "12.00", and how do you turn it into a number?
  2. Why test sale["product"] is None before comparing sale["quantity"]?
  3. When would you use sale.get("discount") instead of sale["discount"]?
  4. What does continue do inside a for loop?
  5. Why does the revenue code keep a list of rejected IDs instead of just skipping them?

Answers

  1. It is a str. float("12.00") converts it to the number 12.0.
  2. Because a record that fails the first rule should not reach any later rule or calculation. Checking for missing values first is a habit worth building: if a value you compare could be None, a comparison such as None > 0 stops the program with a TypeError.
  3. When the key may legitimately not exist. get() returns None instead of raising a KeyError.
  4. It skips the rest of the loop body for the current item and moves on to the next one.
  5. So you can report and investigate what was rejected. Silently dropped records make totals impossible to explain.

Exercise solutions

PythonExercise solutions28 lines
Python
# Exercise 1: revenue per store
revenue_by_store = {}
for sale in transactions:
    if sale["product"] is None or sale["quantity"] <= 0:
        continue
    store = sale["store"]
    line_total = sale["quantity"] * sale["unit_price"]
    revenue_by_store[store] = revenue_by_store.get(store, 0) + line_total

for store, revenue in revenue_by_store.items():
    print(f"{store}: {revenue:.2f}")

# Exercise 2: largest valid line
largest = None
for sale in transactions:
    if sale["product"] is None or sale["quantity"] <= 0:
        continue
    line_total = sale["quantity"] * sale["unit_price"]
    if largest is None or line_total > largest["line_total"]:
        largest = {"transaction_id": sale["transaction_id"], "line_total": line_total}
print(largest["transaction_id"], f"{largest['line_total']:.2f}")

# Exercise 3: notebooks sold
notebooks = 0
for sale in transactions:
    if sale["product"] == "Notebook" and sale["quantity"] > 0:
        notebooks += sale["quantity"]
print("Notebooks sold:", notebooks)
Python28 linesRead-only example cell. Nothing on this page runs code.

revenue_by_store.get(store, 0) returns the running total for that store, or 0 the first time it is seen. .items() loops over the dictionary’s keys and values together. In exercise 2, largest is None handles the very first valid sale, when there is nothing to compare with yet.

Next lesson

You can now hold records in lists and dictionaries, test them with conditions and aggregate them in a loop. In Python Essentials for Data Engineers, Part 2, you will organise this logic into functions, read and write the full CSV file with the standard library, log what happens and build a small batch job that you can rerun safely.

Tags

  • Python
  • CSV
  • Dataset