Python From First Principles
Learn to turn a problem into small, testable steps. Start with values and functions, add decisions and collections, then work with text, files, errors and a complete command-line program.
Meet Python before you write it.
Ever wished the computer would do the boring part for you? Rename a thousand files, sort a ledger or check the same rule all day—Python turns that repeated thought into an instruction.
Python is a general-purpose programming language: a readable set of words and rules for giving a computer instructions. “General-purpose” means it can solve many different kinds of problems instead of doing only one job.
Four words to know
- Code
- The instructions you write for a computer.
- Program
- Code working together to complete a task.
- Interpreter
- The software that reads and runs the instructions in a Python
.pyfile. - Output
- The result a program displays, returns or saves.
What can you make with it?
Python can automate repetitive work, organise files, analyse data, run tests, build command-line tools, and power web APIs or backends. It is also widely used in data science and AI. For a website, Python often handles server-side logic while HTML, CSS and JavaScript create what people use in the browser.
Python needs an interpreter but no account. Follow the free installation guide for Windows, macOS or Ubuntu, then verify it with python --version, py --version or python3 --version.
In this track you will make small, useful terminal programs first: a fare checker, study planner, text analyser, expense ledger and community help-desk. The quick feedback makes each new idea easier to see and test.
One-minute check
A program is a sequence of clear decisions.
Python reads your file from top to bottom. Values have types, variables give those values useful names, and functions group a piece of work so you can call and test it again. Start by making the data transformation correct; connect it to keyboard input later.
def fare_share(total_fare: int, riders: int) -> int:
if total_fare < 0:
raise ValueError("total_fare cannot be negative")
if riders < 1:
raise ValueError("riders must be at least 1")
# Round up so the collected shares cover the fare.
return (total_fare + riders - 1) // riders
share = fare_share(550, 4)
print(f"Each rider contributes KSh {share}") # KSh 138
550 or "Nairobi". A variable is a useful label for a value. A function is a small machine: arguments go in, one job happens, and a result comes back.Keep calculation separate from conversation
input() always returns text. Convert that text at the edge of the program, report a useful error there, and keep the calculation function independent of the terminal. That makes the important logic easy to test.
try:
fare = int(input("Total fare in KSh: "))
print(fare_share(fare, riders=4))
except ValueError as error:
print(f"Check your input: {error}")
Five-minute check
Model the information before writing the loop.
A list keeps an ordered group of items. A dictionary groups named facts about one item. A set keeps unique values. A tuple represents a fixed group you do not intend to change. Choosing the right shape makes the next step easier to read.
tasks = [
{"title": "Read functions", "minutes": 20, "done": False},
{"title": "Build fare check", "minutes": 45, "done": False},
]
def unfinished_titles(items: list[dict]) -> list[str]:
titles = []
for item in items:
if not item["done"]:
titles.append(item["title"])
return titles
Three habits prevent confusing bugs
- Use equality
==to compare values; assignment=gives a name a value. - Do not change a list while iterating over it. Build a new result or iterate over a copy.
- Avoid mutable default arguments such as
def add(item, items=[]). UseNoneand create the list inside.
def add_task(title: str, tasks: list | None = None) -> list:
result = list(tasks) if tasks is not None else []
result.append({"title": title.strip(), "done": False})
return result
Strings are also sequences, but they are immutable: methods such as strip() and lower() return new strings. Keep the returned value when normalising user input.
Why return a new list in this example?
The caller's original list remains unchanged, so the function has a smaller surprise surface. That is especially helpful in beginner programs and tests where hidden shared changes are difficult to trace.
Files fail. Good programs say what happened.
Use pathlib.Path for paths and a with block so files close even if an operation fails. Catch only errors you can handle. A broad except: can hide a spelling mistake or programming bug and make broken data look valid.
import json
from pathlib import Path
def load_expenses(path: Path) -> list[dict]:
if not path.exists():
return []
try:
text = path.read_text(encoding="utf-8")
data = json.loads(text)
except (OSError, json.JSONDecodeError) as error:
raise ValueError(f"Could not read the ledger: {error}") from error
if not isinstance(data, list):
raise ValueError("The ledger must contain a list")
return data
A test is an executable example
import unittest
from fare_budget import fare_share
class FareShareTests(unittest.TestCase):
def test_rounds_up_without_losing_money(self):
self.assertEqual(fare_share(550, 4), 138)
def test_rejects_zero_riders(self):
with self.assertRaises(ValueError):
fare_share(550, 0)
if __name__ == "__main__":
unittest.main()
Run the supplied checks with python -m unittest on Windows or python3 -m unittest on macOS and Linux. When you push an attempt branch, GitHub reports PASS or REVISE automatically. Real-use and explain-back prompts remain useful optional confidence checks.
Fare & Budget Check
Build pure integer-money functions for fare sharing and a daily budget status.
Study Session Planner
Fit structured study tasks into a time box without changing the original data.
Text Insights
Normalise text, count words and rank top terms predictably.
JSON Expense Ledger
Validate, save, load and summarise expense records safely.
Community Help-Desk CLI
Combine functions, collections, search, JSON persistence and tests.
Core-track finish line
The complete note goes deeper.
The full authoring pack is complete locally and is being prepared for protected delivery. It will include the remaining explanations, practice checks, all staged projects and the final combined build. Payment is not active yet.
- Values, variables and expressions
- Decisions and loops
- Functions and scope
- Strings and collections
- Files, JSON and exceptions
- Modules and command-line programs
- Testing and debugging
Primary references reviewed 13 August 2026: Python downloads · Python applications · Python name: official FAQ · Official Python tutorial · Python: errors and exceptions · Python unittest library · PEP 8 style guide. Explanations and examples are original KODE Ń VIBE teaching material.