October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

Python Basics in the Matatu Context: Learn Core Syntax with Invented Route Examples

Learn Python's core syntax through invented matatu route examples covering variables, lists, conditionals, loops, functions and dictionaries, with notes on what the examples do not claim.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can learn the core of Python by writing small programs about an invented matatu route: a name for the route, a list of stops, a teaching fare, and a count of passengers. Each example below teaches one language feature, and every value in it is made up for practice. The examples say nothing about how real matatus price, record or collect fares, and they do not show that any operator or fare system uses Python.

What the matatu examples do and do not claim

Matatus are a useful setting for beginner code because almost everyone can picture a route, a row of stops and a conductor counting passengers. The examples here borrow that picture and nothing more. Routes, stop names, fares and passenger counts are invented, and they are not current, typical, regulated or official values.

As an Amazon Associate I earn from qualifying purchases.

There is real public context to be aware of. Kenya’s Ministry of Roads and Transport describes a planned integrated automated fare collection system that would cover matatus alongside commuter rail and bus rapid transit. In the ministry’s published description, that system is under development rather than completed nationwide, and the description does not say the system is built with Python. Treat the matatu examples as a teaching device, not as a view into how any transport system is programmed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before you start

The official Python Tutorial from the Python Software Foundation opens by stating who it is for: “This tutorial is designed for programmers that are new to the Python language, not beginners who are new to programming.” If you are also new to programming, expect to slow down at the points below where the tutorial moves quickly, especially functions and the idea of a value having a type.

Install Python 3 from python.org, then either type the examples into the interactive interpreter or save them in a file such as matatu.py and run it from a terminal with python matatu.py. Python 3 uses print() as a function, so the examples use the parentheses form.

Step 1: Variables hold values

A variable is a name that refers to a value. Assignment uses a single equals sign, and the name goes on the left.

route_name = "Example Line A"   # invented label
teaching_fare = 20              # invented teaching value, not a real fare
passengers = 3

print(route_name)
print(teaching_fare)

Reassigning a name replaces what it refers to. If a demo route changes its teaching fare, you do not edit the old value; you assign a new one to the same name.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Step 2: Strings, numbers and lists

Strings for text

Text such as a route name goes in single or double quotes. Quotes are required: without them, Python treats the words as names to look up, and you get a NameError.

Numbers for arithmetic

Integers and decimals can be added, multiplied and so on. Two numbers with * give a product, which is the core of a fare total.

Lists for ordered stops

A list keeps items in order and is written with square brackets. Position starts at zero.

stops = ["Riverside", "Market", "Hilltop", "Terminus"]  # invented stop names

print(stops[0])      # Riverside
print(stops[-1])     # Terminus
print(len(stops))    # 4

Step 3: Conditionals make decisions

An if block runs only when its condition is true. elif checks the next condition when the earlier ones are false, and else catches everything left over. The condition line ends with a colon, and the block beneath it is indented.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def classify_load(count):
    if count == 0:
        return "empty"
    elif count <= 5:
        return "light (invented threshold)"
    else:
        return "heavy (invented threshold)"

print(classify_load(0))   # empty
print(classify_load(3))   # light (invented threshold)
print(classify_load(9))   # heavy (invented threshold)

The thresholds are arbitrary teaching numbers. The point is the order of the checks: Python tests conditions from top to bottom and stops at the first one that matches.

Step 4: Loops repeat work

A for loop takes items from a sequence one at a time. A list of stops is the simplest case.

stops = ["Riverside", "Market", "Hilltop", "Terminus"]

for stop in stops:
    print("Next stop:", stop)

Each pass through the loop binds stop to the next item. Anything indented under the for line runs once per item, and the loop ends after the last one.

Step 5: Functions package reusable steps

A function is defined with def, followed by a name, parameters in parentheses and a colon. The body is indented. Parameters are the names that receive values when you call the function, and return sends a value back to the caller.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def show_stops(stops):
    for stop in stops:
        print(stop)

def fare_total(fare, passengers):
    return fare * passengers

show_stops(["Riverside", "Market"])
total = fare_total(20, 3)   # invented teaching fare
print(total)                # 60

What happens without a return

A function with no return statement still runs, but it gives back None. That is Python’s way of saying “no value.” It is a common source of confusion when a student expects a total and gets nothing.

def announce(stop):
    print("Arriving at", stop)

result = announce("Market")   # prints the message
print(result)                 # None

Step 6: Dictionaries and readable style

Once lists feel comfortable, a dictionary can hold related labelled data, such as route metadata. Dictionaries use key-value pairs inside curly braces. Use them after the list examples, because the keys are what make them useful.

route = {
    "name": "Example Line A",     # invented
    "stops": ["Riverside", "Market", "Terminus"],
    "teaching_fare": 20           # invented teaching value
}

print(route["name"])
print(route["stops"][1])          # Market

To loop over both keys and values, call .items(). A passenger record can be modelled the same way.

passengers = {"Amina": 1, "Brian": 2, "Cheptoo": 1}  # invented names and counts

for name, seats in passengers.items():
    print(name, seats)

The official tutorial uses four spaces per indentation level, and it is worth matching that from the first line. Mixing tabs and spaces causes errors that look mysterious until you know to check for them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Modelling a fare payment without touching money

A payment workflow can be represented as a plain record, which is all the examples here do. The function below does not connect to any payment network, bank or mobile-money service; it only builds a text record from values you pass in.

def record_payment(passenger, amount, method):
    return {"passenger": passenger, "amount": amount, "method": method}

receipt = record_payment("Amina", 20, "simulated")  # invented values
print(receipt["amount"])                             # 20

Real payment integration involves provider APIs, authentication and security practices that are well beyond beginner material, so this model stops at the data structure.

Common mistakes and how to fix them

  • IndentationError: a line under def, if, elif, else or for is not indented, or two blocks use different widths. Use four spaces throughout.
  • NameError: a word that should be text is missing its quotes, or a variable was used before it was assigned.
  • Printed None: a function returns nothing. Add a return line if you need its result.
  • Surprising totals: numbers typed in quotes are text, so "20" * 3 repeats the string rather than multiplying. Remove the quotes around fare values.
  • Loop prints once or never: check that the line to repeat is indented under the for line and that the list is not empty.

Where to go next

The official Python Tutorial is free and covers the features used above in more depth, along with the language’s standard style guidance. Beginners who prefer a printed reference can add a physical Python book, which typically goes further into topics the tutorial only touches on. Choose screen or print based on whether you learn better by following along on a computer or by reading away from it. Books are optional; the tutorial alone is enough to work through every step here.

Once these six steps feel natural, change the invented values, add a stop, or write a function that counts how many stops lie before a chosen destination. Each change reinforces the same few ideas.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.