π° Freelancing with Python
in Python
A practical guide to freelancing with Python: project types, finding clients honestly, scoping, proposals, pricing logic, payment terms, invoicing and delivery.
What this lesson is about
Freelancing with Python means selling a result, not selling hours of typing. A small business owner does not care that you know list comprehensions; they care that a report which took them an afternoon every Friday now appears in their inbox by itself. The language is a tool, and the freelancer's real job is to understand a messy problem, agree on what 'done' means, deliver it reliably and be pleasant to work with while doing it.
Most beginners worry about the code and neglect everything around it: finding the right kind of work, estimating honestly, writing a proposal that a stranger can say yes to, agreeing payment terms before work starts, saying no politely to extra requests, and handing the project over so the client is not stuck when you are gone. These are the parts that separate a pleasant one-off job from an unpaid, stressful one. They are also learnable, and much of the thinking can be turned into small Python programs.
This lesson is organised in the order a project unfolds. We look at the kinds of work Python freelancers actually do, how to find clients without hype or spam, how to scope and estimate with a safety buffer, how to write a proposal and think about pricing models, how contracts, invoices and taxes work at a general level, how to communicate and handle scope creep, how to deliver a cleaned CSV as a model deliverable, and the ethics of scraping. I deliberately give no rate figures, because they depend on your country, your skills and the current market; I show you how to compute and research your own instead. Nothing here is legal or tax advice, so always check the rules where you live.
What you will learn
- βRecognise the main kinds of Python freelance work and match them to your skills
- βFind clients honestly through your portfolio, network and well-chosen platforms
- βTurn a vague request into a scoped, estimated piece of work with a safety buffer
- βWrite a short proposal that states deliverables, assumptions and exclusions
- βCompare hourly, fixed-price and retainer models and compute what each really pays
- βUnderstand payment terms, milestones and invoices at a general level using
Decimal - βTrack change requests so scope creep becomes a conversation, not a surprise
- βDeliver and hand over work with documentation and a checklist, and respect scraping limits
Why programmers should learn this
- β Freelancing lets you turn skills you already have, such as scripting, spreadsheets and data cleaning, into paid work without waiting for a job title.
- β Real client projects teach things tutorials cannot: unclear requirements, messy data, deadlines and the need to explain technical choices to non-technical people.
- β Good scoping and estimating protect you from the most common freelance failure, which is working far more hours than you were paid for.
- β Clear contracts, milestones and invoices protect the client as well, which is why careful freelancers tend to get repeat work and referrals.
- β Every delivered project becomes a portfolio piece and a story you can tell in interviews, even if you later move to a full-time role.
What kinds of Python work can you sell?
Python freelance work clusters into a handful of families. Automation covers renaming and sorting files, producing reports, filling spreadsheets and sending scheduled emails. Data cleaning and analysis takes a client's untidy exports and turns them into tables, charts and summaries. Scraping and data collection gathers public information into a structured file, within the limits we discuss at the end of this lesson. Small web tools and APIs are simple dashboards, form handlers and integrations between two services. Scripting for other people's systems includes bots, notebooks and glue code. Machine learning work exists too, but it is rarer at the beginner level and usually needs more evidence of experience.
The useful question is not 'what is the most impressive thing I can claim' but 'which problems can I already solve reliably, and who has them'. Small organisations, researchers, shop owners, teachers and agencies often have repetitive computer work and no developer on staff. If you can read and write files, work with tables and explain what you did, you already cover a large share of their needs. See Excel automation, email automation and pandas for the technical building blocks.
The snippet below is a tiny fit checker. Each project type lists the skills it usually needs, you list the skills you can honestly demonstrate, and the program shows how much of each type you cover and what is missing. It is deliberately simple, but doing this exercise on paper before you write a profile will stop you from applying for work you cannot yet deliver.
PROJECT_TYPES = {
"Spreadsheet automation": {"python basics", "csv", "excel files", "pandas"},
"Data cleaning": {"python basics", "csv", "pandas", "regex"},
"Web scraping": {"python basics", "http", "html parsing", "csv", "ethics"},
"Small web tool": {"python basics", "flask or fastapi", "html", "deployment"},
"Report by email": {"python basics", "pandas", "email", "scheduling"},
}
my_skills = {"python basics", "csv", "pandas", "regex", "email"}
for name in sorted(PROJECT_TYPES):
needed = PROJECT_TYPES[name]
have = needed & my_skills
missing = sorted(needed - my_skills)
percent = round(100 * len(have) / len(needed))
print(f"{name:<24} {percent:>3}% missing: {missing}")Data cleaning 100% missing: [] Report by email 75% missing: ['scheduling'] Small web tool 25% missing: ['deployment', 'flask or fastapi', 'html'] Spreadsheet automation 75% missing: ['excel files'] Web scraping 40% missing: ['ethics', 'html parsing', 'http']
Line by line
- 1-7A dictionary maps each kind of work to a set of skills it normally requires. Sets make it easy to compare skills later.
- 9The skills I can honestly demonstrate, also stored as a set.
- 11Loop over the project names in alphabetical order so the output is stable.
- 12-14
needed & my_skillsis set intersection (skills I have);needed - my_skillsis set difference (skills I lack). The result is sorted for a tidy display. - 15-16Turn the overlap into a rounded percentage and print one aligned line per project type.
The percentages are not a scientific measure. They are a prompt for a conversation with yourself: for any type above roughly three quarters, you could probably deliver a small first job; for the rest you have a clear learning list.
Pick one or two project types and become known for them. 'I clean messy spreadsheet exports and automate weekly reports' is easier for a stranger to hire than 'I do everything in Python'.
Finding clients honestly
Clients rarely arrive because you posted once. They arrive because they can see evidence that you solve problems like theirs and because someone they trust pointed them to you. The honest, durable sources are your own network (people who already know you), a small portfolio with two or three clearly explained projects (see portfolio and GitHub), communities where you help people for free before you ever pitch, and freelance marketplaces where you write careful, specific proposals instead of copying the same message to fifty listings.
Honesty is also practical. Do not claim experience you do not have, do not promise delivery dates you cannot meet and do not invent testimonials. If you have no clients yet, say so, and offer a small paid pilot with a clear scope, or build a demonstration project from a realistic problem and describe it as exactly that. Prospective clients can usually tell the difference between a real result and decoration, and a modest but true profile builds trust faster.
Marketplaces have their own rules about fees, messaging outside the platform and what counts as a proper contract. Read those terms before relying on them, and compare more than one platform. Your chance of being hired rises when your first message shows you read the listing: it restates their problem in your words, asks one useful question and proposes a first small step.
Follow-up is where many freelancers lose work, simply because they forget. A tiny tracker like the one below records who you contacted and when, then lists the people who are due a polite follow-up. It uses datetime.date and timedelta so the arithmetic is exact, and a fixed 'today' so the output is the same every time.
from datetime import date, timedelta
TODAY = date(2026, 3, 16) # fixed for a repeatable demo
FOLLOW_UP_AFTER = timedelta(days=7)
leads = [
{"name": "Bakery owner", "contacted": date(2026, 3, 2), "replied": False},
{"name": "Research lab", "contacted": date(2026, 3, 12), "replied": False},
{"name": "Online shop", "contacted": date(2026, 3, 1), "replied": True},
{"name": "Local school", "contacted": date(2026, 3, 9), "replied": False},
]
for lead in leads:
due = lead["contacted"] + FOLLOW_UP_AFTER
if lead["replied"]:
status = "replied - continue the conversation"
elif due <= TODAY:
status = f"follow up now (was due {due.isoformat()})"
else:
status = f"wait until {due.isoformat()}"
print(f"{lead['name']:<14} {status}")Bakery owner follow up now (was due 2026-03-09) Research lab wait until 2026-03-19 Online shop replied - continue the conversation Local school follow up now (was due 2026-03-16)
Line by line
- 1Import
datefor calendar dates andtimedeltafor a span of days. - 3-4Fix 'today' so the output never changes; in real use you would call
date.today(). The follow-up gap is a seven-daytimedelta. - 6-11Each lead is a small dictionary recording who, when I first wrote and whether they answered.
- 13Loop over the leads.
- 14Adding a
timedeltato adategives the date the follow-up is due. - 15-20Choose a status: leads who replied need a real conversation, overdue ones need a nudge, the rest should simply wait.
- 21Print the name padded to 14 characters so the statuses line up.
Follow up once or twice, politely, then stop. Repeating the same message every day is spam, and it harms your reputation on any platform.
Scoping and estimating with a buffer
Scoping means writing down exactly what you will deliver, what you will not deliver and what you are assuming. A request such as 'we need a script to clean our sales data' hides many questions. How many files, and in what format? What does clean mean: removing duplicates, fixing dates, normalising names? Who will run it, on which computer and how often? What happens when the input is wrong? Every unanswered question is a place where the hours can grow.
Estimating is a separate skill. Break the job into small tasks you can picture doing, and for each give three numbers: an optimistic time if everything goes smoothly, a most likely time and a pessimistic time if something goes wrong. A common way to combine them is the weighted average (optimistic + 4 times most likely + pessimistic) divided by 6, often called a three-point or PERT estimate. It leans toward the most likely value but still respects the bad case.
Then add a buffer for the things you cannot list: unclear requirements, waiting for answers, bugs in the client's data, meetings and the final handover. How big the buffer should be depends on how well you understand the work, so use your own records of past projects to calibrate it. The calculator below takes task estimates, applies the formula, adds a percentage buffer and rounds the total up to the next half hour. The buffer percentage here is just a parameter you can change.
import math
tasks = [
# (task, optimistic, likely, pessimistic) in hours
("Understand the data and questions", 1.0, 2.0, 4.0),
("Write the cleaning script", 2.0, 4.0, 8.0),
("Build the weekly summary report", 1.5, 3.0, 6.0),
("Test on real files and fix issues", 1.0, 2.0, 5.0),
("Write instructions and hand over", 0.5, 1.0, 2.0),
]
BUFFER = 0.20 # 20 percent safety margin: calibrate from your own history
def expected(o, m, p):
return (o + 4 * m + p) / 6
total = 0.0
for name, o, m, p in tasks:
e = expected(o, m, p)
total += e
print(f"{name:<36} {e:5.2f} h")
with_buffer = total * (1 + BUFFER)
rounded = math.ceil(with_buffer * 2) / 2 # round UP to a half hour
print(f"{'Sum of expected values':<36} {total:5.2f} h")
print(f"{'With buffer':<36} {with_buffer:5.2f} h")
print(f"{'Quoted effort':<36} {rounded:5.1f} h")Understand the data and questions 2.17 h Write the cleaning script 4.33 h Build the weekly summary report 3.25 h Test on real files and fix issues 2.33 h Write instructions and hand over 1.08 h Sum of expected values 13.17 h With buffer 15.80 h Quoted effort 16.0 h
Line by line
- 1
mathgives usceil, used to round up rather than to the nearest value. - 3-9Each task is a tuple with three estimates in hours. The tuple layout is spelled out in the comment.
- 10A single buffer percentage kept in one named constant so it is easy to change.
- 12-13The weighted three-point formula as a small function.
- 15-19Add up the expected time per task and print each line, formatting hours to two decimals.
- 21Multiply by
1 + BUFFERto add the safety margin. - 22Multiplying by 2, taking
ceiland dividing by 2 rounds up to the next half hour. - 24-26Print the totals so you can see how the number moves from raw estimate to quoted effort.
Estimates are not promises. Tell the client what the estimate assumes, and say that if the assumptions change, the estimate changes too.
Writing a proposal people can say yes to
A good proposal is short and specific. It starts with the client's problem in their own words, so they know you listened. It then lists the deliverables (what they will receive), the assumptions (what you expect to be true, such as 'the input files use the same columns every month'), the exclusions (what is not included), the timeline, the price and how payment works. The exclusions section feels awkward to write, yet it is the most useful part when a disagreement comes later.
Avoid jargon and avoid promising technical methods the client does not care about. Writing that you will use a particular library tells them nothing; writing that they will drag a file into a folder and get a clean spreadsheet back tells them everything. If you are unsure of any detail, state it as a question or an assumption instead of silently guessing.
You will write several proposals, so a template saves time, but each one still needs real content for that client. The code below builds a plain-text proposal from a dictionary. Keeping the facts in data and the layout in code makes it easy to produce a consistent document, and textwrap keeps long lines readable.
import textwrap
proposal = {
"client": "Green Valley Bakery",
"problem": "Sales exports from two tills must be combined and cleaned by hand every week.",
"deliverables": [
"A Python script that merges and cleans the two weekly CSV exports",
"A one-page summary file with totals per product",
"Short written instructions for running the script",
],
"assumptions": [
"Both exports keep the same column names each week",
"The script runs on one Windows computer with Python already installed",
],
"exclusions": [
"Changes to the till software",
"Automatic scheduling (can be quoted separately)",
],
"timeline": "Delivery about one week after the sample files and answers are received",
}
def section(title, items):
lines = [title.upper()]
for item in items:
lines.append(textwrap.fill(item, width=60, initial_indent=" - ",
subsequent_indent=" "))
return "\n".join(lines)
print(f"PROPOSAL FOR {proposal['client'].upper()}")
print(textwrap.fill(proposal["problem"], width=64))
print()
for key in ("deliverables", "assumptions", "exclusions"):
print(section(key, proposal[key]))
print()
print("TIMELINE")
print(textwrap.fill(proposal["timeline"], width=64, initial_indent=" "))PROPOSAL FOR GREEN VALLEY BAKERY
Sales exports from two tills must be combined and cleaned by
hand every week.
DELIVERABLES
- A Python script that merges and cleans the two weekly
CSV exports
- A one-page summary file with totals per product
- Short written instructions for running the script
ASSUMPTIONS
- Both exports keep the same column names each week
- The script runs on one Windows computer with Python
already installed
EXCLUSIONS
- Changes to the till software
- Automatic scheduling (can be quoted separately)
TIMELINE
Delivery about one week after the sample files and answers are
receivedLine by line
- 1
textwrapwraps long text to a fixed width. - 3-21All proposal facts live in a dictionary: a problem statement, lists of deliverables, assumptions and exclusions, and a timeline.
- 23-28
sectionmakes a heading in capitals, then one wrapped bullet per item.initial_indentstarts the first line andsubsequent_indentlines up wrapped continuation lines. - 30-31Print the title and the problem statement wrapped to 64 characters.
- 33-35Loop over the three list sections in a fixed order, printing each followed by a blank line.
- 36-37Print the timeline with an indent.
Notice that price is not in this template. How you present price depends on the pricing model, which is the next topic.
Pricing models: how to think and compute
There are three common ways to charge. Hourly pricing bills the time you spend; it is simple and fair when the scope is unclear, but it rewards slowness and makes clients nervous about the total. Fixed price quotes one amount for a defined deliverable; clients like certainty, and you profit when you work efficiently, but you carry the risk of underestimating. A retainer is a recurring fee for ongoing availability or maintenance, useful for reports and systems that need regular attention. Many freelancers mix them: fixed for the build, hourly or retainer for changes afterwards.
I will not give you a number to charge, because any figure I printed would be wrong for someone. Rates vary by country, by skill and by market, and they change over time. To find a sensible range, look at current job listings and freelance marketplace profiles for similar work, ask people in communities you belong to, and compare what comparable freelancers publish. Treat what you find as a starting range, and adjust it as you gain evidence.
What I can show you is the arithmetic. Start from what you need to earn in a period, add your costs and the time you set aside for taxes and unpaid days, and divide by the hours you can realistically bill. Billable hours are always fewer than working hours, because finding clients, emailing, invoicing and learning are unpaid. The second half of the code shows the reverse check: a fixed price divided by the hours you actually spent gives your real hourly rate. The figures in the code are placeholders in any currency, chosen only to make the arithmetic easy to follow.
# PLACEHOLDER numbers only: replace every value with your own research.
income_wanted = 2000 # what you want to take home per month
costs = 300 # tools, internet, software, equipment share
tax_reserve_rate = 0.20 # share of earnings you set aside; check local rules
working_hours = 120 # hours you actually work per month
billable_share = 0.60 # fraction of working hours you can bill
gross_needed = (income_wanted + costs) / (1 - tax_reserve_rate)
billable_hours = working_hours * billable_share
break_even_rate = gross_needed / billable_hours
print(f"Gross needed: {gross_needed:.2f}")
print(f"Billable hours: {billable_hours:.1f}")
print(f"Break-even hourly rate: {break_even_rate:.2f}")
# Reverse check: what does a fixed price really pay per hour?
fixed_price = 400
estimated_hours = 8
actual_hours = 14
print(f"Planned hourly: {fixed_price / estimated_hours:.2f}")
print(f"Real hourly: {fixed_price / actual_hours:.2f}")Gross needed: 2875.00 Billable hours: 72.0 Break-even hourly rate: 39.93 Planned hourly: 50.00 Real hourly: 28.57
Line by line
- 1-6Placeholder inputs. The comment is a reminder that these are not recommendations; each one is a question you should answer for yourself.
- 8Divide by
1 - tax_reserve_rateto find the gross amount that leaves your wanted income plus costs after setting money aside. - 9Billable hours are only a fraction of working hours.
- 10The break-even rate: gross money needed divided by billable hours. Pricing below this loses money in the long run.
- 12-14Print the three results with fixed decimal places.
- 17-20Compare the hourly rate you planned with what a fixed price produced after the job took longer than estimated.
Record your actual hours on every project, even fixed-price ones. After a few jobs you will know how far your estimates drift and can set your buffer from evidence.
Contracts, payment terms, invoices and taxes (general ideas)
I am not a lawyer or an accountant, and the rules differ by country, so treat this section as a checklist of topics to look up locally. A written agreement, even a short one, should name the parties, describe the deliverables, state the price and payment schedule, say who owns the finished work and when ownership passes, explain how changes are handled and give a way to end the arrangement. Many freelancers take a deposit before starting and split larger jobs into milestones, so neither side is exposed for too long. If a job is large or unusual, pay for a professional to review the document.
Money handling is easiest to get right when you use exact decimal arithmetic. Python's floating-point numbers cannot represent values such as 0.10 exactly, and small errors in invoices look unprofessional and can cause real disputes. The standard library's decimal.Decimal stores decimal fractions exactly and lets you choose a rounding rule. Always build Decimals from strings, never from floats, and round only at the end of a calculation. See numbers and floating-point for background.
The first block below splits a project total into a deposit and equal milestones while guaranteeing that the parts add up to the total, with any leftover cent placed on the final payment. The second generates a text invoice: line items, a subtotal, a tax line using a placeholder rate (look up the correct treatment for your place and client) and a total. Invoices normally also carry an invoice number, dates, both parties' details and payment instructions, plus whatever your local rules require.
Taxes deserve the same care. Freelancers are commonly responsible for tracking income and expenses, registering where required, setting money aside, and filing on time. Keep every invoice and receipt in a folder, separate business money from personal money if you can, and ask a local accountant or the official tax authority's guidance what applies to you.
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")
def schedule(total, deposit_share, milestones):
total = Decimal(total)
deposit = (total * Decimal(deposit_share)).quantize(CENT, ROUND_HALF_UP)
remaining = total - deposit
each = (remaining / milestones).quantize(CENT, ROUND_HALF_UP)
payments = [("Deposit", deposit)]
for i in range(1, milestones + 1):
payments.append((f"Milestone {i}", each))
drift = total - sum(amount for _, amount in payments)
name, amount = payments[-1]
payments[-1] = (name, amount + drift)
return payments
for label, amount in schedule("1000.00", "0.30", 3):
print(f"{label:<12} {amount:>8}")
print("Sum:", sum(a for _, a in schedule("1000.00", "0.30", 3)))Deposit 300.00 Milestone 1 233.33 Milestone 2 233.33 Milestone 3 233.34 Sum: 1000.00
Line by line
- 1Import
Decimaland a rounding rule that rounds halves upward, the way most people expect. - 3
CENTis the precision we want: two decimal places. - 5-6The function takes text inputs and converts the total to a
Decimal. - 7Compute the deposit and round it to cents with
quantize. - 8-9The remainder is split evenly and rounded.
- 10-12Build the list of payments, starting with the deposit and adding one entry per milestone.
- 13-15Rounding can leave the sum a cent off, so calculate the difference and add it to the last payment. Now the schedule always adds up exactly.
- 18-20Print each payment aligned in columns, then the sum as a check.
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")
TAX_RATE = Decimal("0.10") # placeholder: use the rule that applies to you
items = [
("Data cleaning script", Decimal("6"), Decimal("20.00")),
("Weekly summary report", Decimal("3.5"), Decimal("20.00")),
("Handover notes", Decimal("1"), Decimal("15.50")),
]
def money(x):
return x.quantize(CENT, ROUND_HALF_UP)
print("INVOICE 2026-001")
print(f"{'Description':<24}{'Qty':>6}{'Price':>9}{'Amount':>10}")
subtotal = Decimal("0")
for desc, qty, price in items:
amount = money(qty * price)
subtotal += amount
print(f"{desc:<24}{qty:>6}{price:>9}{amount:>10}")
tax = money(subtotal * TAX_RATE)
print(f"{'Subtotal':<39}{subtotal:>10}")
print(f"{'Tax':<39}{tax:>10}")
print(f"{'TOTAL':<39}{subtotal + tax:>10}")INVOICE 2026-001 Description Qty Price Amount Data cleaning script 6 20.00 120.00 Weekly summary report 3.5 20.00 70.00 Handover notes 1 15.50 15.50 Subtotal 205.50 Tax 20.55 TOTAL 226.05
Line by line
- 1-4Import Decimal tools and set a placeholder tax rate as a
Decimalbuilt from a string. - 6-10Line items are tuples of description, quantity and unit price, all exact decimals.
- 12-13A small helper rounds any amount to cents so we do it the same way every time.
- 15-16Print a title and a header row; the format specs pad and right-align columns.
- 17-21Loop over lines, round each line total, add it to the running subtotal and print the row.
- 23Tax is computed once on the subtotal and rounded.
- 24-26Print subtotal, tax and the grand total in aligned columns.
Tax rules, invoice requirements and contract law differ by country and by situation. Use this lesson to know what to ask, then confirm the details with official sources or a qualified professional.
Communication and scope creep
Most freelance disputes are communication failures, not coding failures. Confirm important decisions in writing, even if they were agreed on a call: a short message that says 'to confirm, I will deliver X by Friday and you will send Y by Wednesday' costs a minute and prevents arguments. Share progress early with something the client can look at, because feedback on a rough version is cheaper than feedback on the finished one. Keep your tone calm and plain, and say clearly when you are waiting on them.
Scope creep is the slow growth of a project through small extra requests: 'could it also handle this column', 'can you make it run on my laptop too'. None of them sounds large, yet together they can double the work. The cure is not refusing everything. Compare each request with the agreed deliverables, decide whether it is included or new, and if it is new, offer a choice: add it with extra time and cost, swap it for something else, or put it in a later phase. Most clients are reasonable when the trade-off is explained kindly and early.
The tracker below keeps each change request as data. It compares requests to the original list of deliverables, assigns hours to new items and shows the effect on the quote. The rate is a placeholder, and the point is to have a neutral record that makes the conversation factual.
from decimal import Decimal
INCLUDED = {"merge weekly files", "clean dates", "totals per product"}
HOURLY = Decimal("25.00") # placeholder rate for change requests
requests = [
("clean dates", 0),
("export totals as a chart", 2),
("merge weekly files", 0),
("run automatically every Monday", 3),
("add a customer column", 1),
]
extra_hours = 0
print("Change log")
for text, hours in requests:
if text in INCLUDED:
print(f" in scope : {text}")
else:
extra_hours += hours
print(f" NEW (+{hours}h): {text}")
extra_cost = HOURLY * extra_hours
print(f"Extra hours: {extra_hours}")
print(f"Extra cost at the agreed change rate: {extra_cost:.2f}")Change log in scope : clean dates NEW (+2h): export totals as a chart in scope : merge weekly files NEW (+3h): run automatically every Monday NEW (+1h): add a customer column Extra hours: 6 Extra cost at the agreed change rate: 150.00
Line by line
- 1Decimal keeps the cost arithmetic exact.
- 3A set of deliverables both sides agreed on. Membership tests on sets are fast and read clearly.
- 4A placeholder hourly rate for additional work, which you would agree in the contract.
- 6-12Each request is a tuple: the wording and my estimate of extra hours (zero if already included).
- 14-15Start the running total and print a heading.
- 16-21If the request is one of the agreed items, report it as in scope; otherwise add its hours and flag it as new.
- 23-25Multiply the extra hours by the rate and print both numbers for the client conversation.
Say yes to the goal and name the cost of the method: 'Yes, I can add that. It is outside the original list, so here is the extra time. Shall I go ahead?'
Delivery: a cleaned CSV and a handover checklist
Delivery is more than sending a file. A good deliverable is correct, reproducible, documented and easy for the client to use without you. Take the common job of cleaning a messy export: trim stray spaces, normalise capitalisation, parse dates written in different styles, convert amounts to numbers, remove exact duplicate rows and, importantly, produce a small report of what you changed and what you could not fix. That report is part of the product, because it shows the client you did not silently throw data away.
The first example below reads a deliberately messy CSV from a string, cleans it using only the standard library and prints both the clean rows and a change report. In a real job you would read the client's file with open() and might use pandas for larger tables (see JSON and CSV and pandas). Notice that unparseable values are reported, not guessed.
The second example generates a handover checklist. Before you call a project finished, check that the client has the final files, the instructions, the steps to rerun things, a note of which accounts and keys are involved, and agreement on what happens if something breaks. Producing the list from a function means every project gets the same careful ending.
import csv
import io
from datetime import datetime
RAW = """name , date,amount
alice SMITH,2026-03-01, 12.50
BOB jones,03/02/2026,8
alice smith,2026-03-01,12.50
Carol Diaz,not a date,5.25
"""
DATE_FORMATS = ("%Y-%m-%d", "%m/%d/%Y")
def parse_date(text):
for fmt in DATE_FORMATS:
try:
return datetime.strptime(text.strip(), fmt).date().isoformat()
except ValueError:
pass
return None
reader = csv.DictReader(io.StringIO(RAW))
reader.fieldnames = [f.strip() for f in reader.fieldnames]
clean, seen, report = [], set(), []
for number, row in enumerate(reader, start=2):
name = " ".join(row["name"].split()).title()
date = parse_date(row["date"])
amount = float(row["amount"].strip())
if date is None:
report.append(f"line {number}: unreadable date {row['date']!r}, row kept with empty date")
key = (name, date, amount)
if key in seen:
report.append(f"line {number}: duplicate of an earlier row, removed")
continue
seen.add(key)
clean.append({"name": name, "date": date or "", "amount": f"{amount:.2f}"})
out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=["name", "date", "amount"])
writer.writeheader()
writer.writerows(clean)
print(out.getvalue())
print("Report:")
for line in report:
print(" -", line)name,date,amount Alice Smith,2026-03-01,12.50 Bob Jones,2026-03-02,8.00 Carol Diaz,,5.25 Report: - line 4: duplicate of an earlier row, removed - line 5: unreadable date 'not a date', row kept with empty date
Line by line
- 1-3Import
csvfor reading and writing,ioto treat a string like a file anddatetimefor date parsing. - 5-10A deliberately messy sample: stray spaces in headers and names, two date styles, a bad date, a duplicate row and mixed capitalisation.
- 12Date formats we accept, tried in order.
- 14-20Try each format;
strptimeraisesValueErrorwhen it does not match, so we catch it and move on. Return an ISO date orNone. - 22-23Create a
DictReaderand strip whitespace from the header names. - 25Prepare the clean rows, a set of already-seen keys and the change report.
- 26-29Number rows starting at 2 (line 1 is the header).
split()thenjoincollapses repeated spaces andtitle()fixes capitalisation. - 30-31Report any date we cannot read instead of guessing.
- 32-36Build a key from the cleaned values; if we saw it before, log and skip it, otherwise remember it.
- 37Append the cleaned row, formatting the amount with two decimals.
- 39-43Write the clean rows to an in-memory CSV and print it.
- 44-46Print the report, which you would send with the file.
def handover_checklist(project, uses_accounts=False, runs_on_schedule=False):
items = [
"Final files delivered and the client confirmed they open",
"Source code and a short README with run instructions sent",
"List of required software and versions written down",
"Sample input and expected output included",
"How to report a problem, and what is covered after delivery",
"Final invoice sent and payment terms restated",
]
if uses_accounts:
items.append("Accounts, keys and passwords owned by the client, not by me")
if runs_on_schedule:
items.append("Schedule documented and how to pause or stop it")
lines = [f"Handover checklist: {project}"]
for number, item in enumerate(items, start=1):
lines.append(f"[ ] {number}. {item}")
return "\n".join(lines)
print(handover_checklist("Bakery sales cleaner"))
print()
print(handover_checklist("Weekly report emailer", uses_accounts=True, runs_on_schedule=True))Handover checklist: Bakery sales cleaner [ ] 1. Final files delivered and the client confirmed they open [ ] 2. Source code and a short README with run instructions sent [ ] 3. List of required software and versions written down [ ] 4. Sample input and expected output included [ ] 5. How to report a problem, and what is covered after delivery [ ] 6. Final invoice sent and payment terms restated Handover checklist: Weekly report emailer [ ] 1. Final files delivered and the client confirmed they open [ ] 2. Source code and a short README with run instructions sent [ ] 3. List of required software and versions written down [ ] 4. Sample input and expected output included [ ] 5. How to report a problem, and what is covered after delivery [ ] 6. Final invoice sent and payment terms restated [ ] 7. Accounts, keys and passwords owned by the client, not by me [ ] 8. Schedule documented and how to pause or stop it
Line by line
- 1The function takes a project name and two flags for optional extras.
- 2-9The base list every project gets: files, README, requirements, samples, support terms and the final invoice.
- 10-13Extra items appear only when they apply: credentials the client must own, and schedules that need to be documented.
- 14-17Build the output lines with a check box and a number for each item.
- 18Join lines with newlines to return one string.
- 20-22Print two checklists, one for a simple job and one with both flags set.
Never keep a client's passwords or API keys in your own code or repository. Use environment variables and tell the client how to set them.
Scraping and data-collection ethics
Web scraping is a popular freelance service and also the area where good judgement matters most. Being technically able to fetch a page does not mean you are allowed to use what is on it. Before accepting a scraping job, check the site's terms of service, look at its robots.txt file, ask whether there is an official API or a data export you could use instead, and think about whether the data includes personal information. Rules about personal data and copyright differ between countries, so when in doubt, ask the client to confirm permission in writing or decline the job.
Be a considerate visitor even when scraping is allowed. Identify your program honestly in the request headers, fetch slowly with pauses between requests, cache what you have already downloaded so you do not repeat requests, stop if the site asks you to and never try to defeat logins, paywalls or blocking measures. Collect only what the project needs. Our web scraping lesson and the advanced scraping lesson cover the techniques; this lesson is about deciding whether and how to use them.
Python ships with urllib.robotparser, which reads robots.txt rules. The example below feeds it a sample file as text, so it runs offline, and asks whether specific paths may be fetched by a bot called ClientBot. Remember that robots.txt expresses the site owner's wishes about automated access and is not a substitute for reading the terms or for legal advice.
from urllib.robotparser import RobotFileParser
SAMPLE = """User-agent: *
Disallow: /private/
Disallow: /cart
Crawl-delay: 5
User-agent: BadBot
Disallow: /
"""
parser = RobotFileParser()
parser.parse(SAMPLE.splitlines())
paths = ["/products/shoes", "/private/orders", "/cart", "/about"]
for path in paths:
allowed = parser.can_fetch("ClientBot", path)
print(f"{path:<18} {'allowed' if allowed else 'blocked'}")
print("Blocked bot:", parser.can_fetch("BadBot", "/about"))
print("Requested delay:", parser.crawl_delay("ClientBot"), "seconds")/products/shoes allowed /private/orders blocked /cart blocked /about allowed Blocked bot: False Requested delay: 5 seconds
Line by line
- 1Import the standard-library parser for
robots.txtrules. - 3-9A sample
robots.txtas text: everyone is asked to avoid/private/and/cartand to wait 5 seconds between requests, and one named bot is excluded entirely. - 11-12Create the parser and feed it the lines of the file. No network access is needed.
- 14-17Ask
can_fetchwhether our bot may request each path and print a readable verdict. - 19A bot with its own rule is blocked from everything.
- 20
crawl_delayreturns the requested pause, which your scraper should respect between requests.
If a client asks you to collect private data, bypass a login, or ignore a site's stated rules, decline. A refused job costs you less than a legal or reputational problem.
Common mistakes
β Quoting a price before understanding the work
A number given in the first message is hard to retract. Ask about files, formats, frequency and what 'done' means, then estimate. A short call or a list of questions is not wasted time; it is the cheapest part of the project.
β Estimating without a buffer
Real projects include waiting, unclear requirements and surprises in the client's data. If your quote equals the hours you imagine on a perfect day, you will lose money on a normal one. Calibrate a buffer from your own recorded hours.
β Starting before payment terms are clear
Agree the price, deposit, milestones and what counts as final approval in writing before you start. Without it, a small disagreement at the end becomes an argument about everything.
β Letting scope creep happen quietly
Doing small extras for free sets a precedent. Compare each new request to the agreed deliverables and offer the client a clear choice: extra cost, a swap, or a later phase.
β Using floats for money or guessing when cleaning data
Floats cannot represent most decimal fractions exactly, so invoices drift by cents; use Decimal built from strings. Likewise, never silently invent or drop data when cleaning: report what you could not fix.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What is the main purpose of an 'exclusions' section in a proposal?
Q2. In a three-point estimate, which formula combines optimistic (o), likely (m) and pessimistic (p) values?
Q3. Why should you build Decimal values from strings such as Decimal('0.10')?
Decimal(0.1) preserves that inexactness, whereas Decimal('0.1') is exact.Q4. Your fixed-price job took more hours than planned. Which calculation shows your real hourly earnings?
Q5. A client sends a new request that is not in the agreed deliverables. What is the best response?
Q6. What does robots.txt tell you?
Frequently asked questions
How do I get my first client with no experience?
+Build two or three small projects that solve realistic problems and describe them clearly in a portfolio, tell people you know what you offer, and answer questions in communities where your future clients gather. Offer a small, well-scoped first job and be honest about your experience. See the portfolio lesson for how to present your work.
What should I charge?
+I cannot give a number, because it depends on your country, skills and market, and it changes. Research current listings and profiles for similar work, compute your own break-even rate with the formula in this lesson, and record your real hours so you can adjust. Start within a range you can defend and raise it as your evidence grows.
Should I choose hourly or fixed pricing?
+Use hourly or time-and-materials when the scope is unclear or likely to change, and fixed price when you can define the deliverable precisely and you have estimated similar work before. A retainer suits ongoing maintenance. Whatever you pick, state it in the proposal and define how changes are priced.
Do I need a contract for a small job?
+A short written agreement is wise even for small jobs, because it records scope, price, payment dates and ownership. The rules differ by place, so check local requirements and consider professional review for larger or unusual work. This lesson is general information, not legal advice.
How do I handle taxes as a freelancer?
+Requirements vary widely: you may need to register, track income and expenses, collect or report certain taxes and file on a schedule. Keep all invoices and receipts, set aside part of each payment, and consult your local tax authority's official guidance or an accountant.
Key takeaways
- βSell results, not hours, and focus on a small set of project types you can deliver reliably.
- βFind clients through honest evidence: portfolio, network, helpful community work and specific proposals.
- βScope in writing, estimate tasks with three points, and add a buffer calibrated from your own records.
- βChoose hourly, fixed or retainer pricing deliberately, compute your break-even rate and research current market ranges instead of guessing.
- βUse deposits, milestones and exact
Decimalinvoices, and check local contract and tax rules. - βTreat changes as trade-offs, deliver documented work with a handover checklist, and respect scraping terms and privacy.