Skip to main content

Programming fundamentals · Beginner · 16 min

Write pseudocode before you code

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will plan a bus-fare calculator in pseudocode, trace it by hand to find and fix a gap in the plan, draw it as a flowchart and turn it line by line into a Python script that gives the same answers.

On this page

Most bugs a beginner writes are not typing mistakes. They are decisions nobody made: what should happen when the list is empty, when the number is zero, when two rules disagree. Pseudocode is a way to make those decisions before you write code, in plain language you can check with a pencil.

Pseudocode is a plan for a program written as short lines in plain language: get this, work that out, if this then that, repeat for each item. It has no fixed grammar and no computer runs it. Its value is that it is fast to write, cheap to change and readable by people who do not code, such as the product manager or the client who owns the rules.

In this tutorial you plan a bus-fare calculator. A rider takes several journeys in a day; each journey costs more the more fare zones it crosses, students pay half, and there is a daily cap. You write the plan, test it by hand, find a place where it gives the wrong answer, fix the plan, draw it as a flowchart, and only then write about 40 lines of Python. Steps 1 to 5 need no computer at all, so you can do them on paper on a bus, or on a phone with no data left.

Amounts are whole units of any currency; the examples use a 300 single-zone fare.

Step 1 · Write down the inputs, outputs and rules

Before any steps, write down three things: what goes in, what comes out, and the rules that connect them. On paper or in a text file, write:

Text
PROBLEM
  Work out what a rider pays for each bus journey in one day.

INPUTS
  rider type: adult or student
  journeys: a list, one entry per journey, each the number of fare zones crossed

OUTPUTS
  the charge for each journey
  the total paid today

RULES
  1 zone costs 300, 2 zones cost 450, 3 or more zones cost 600
  students pay half fare
  nobody pays more than the daily cap in one day: 1000 for adults, 500 for students
  zones must be a whole number of 1 or more

Each part has a job:

  • Inputs are everything the program is told. If a rule needs a fact that is not in this list (the time of day, say), either the rule or the inputs are wrong.
  • Outputs are what the program must produce. Writing them first stops you building something that works but answers a different question.
  • Rules are the business logic, in the words of whoever owns them. Copy them as given; do not tidy them into what you think they mean yet.

Check it worked

You have four headed sections. Every rule mentions only things listed under inputs (zones, rider type) or things it defines itself (fare, cap). Every output can be worked out from the inputs using the rules.

Step 2 · Turn the rules into steps

Now write the steps in the order a computer would follow them. Use a small set of capitalised keywords so the structure stands out, and indent lines that belong inside a decision or a loop:

  • INPUT and OUTPUT for data coming in and going out
  • SET name TO value to remember a value under a name
  • IF ... THEN, ELSE IF, ELSE for decisions
  • `FOR EACH ... ` for doing something once per item in a list
  • STOP to end early with a message

Write this first version:

Text
INPUT rider type and the list of journeys
IF rider type is not adult or student, or there are no journeys THEN
    STOP with a usage message
FOR EACH journey
    IF zones is not a whole number of 1 or more THEN
        STOP with "zones must be a whole number of 1 or more"

SET cap TO 1000
IF rider is student THEN
    SET cap TO 500
SET spent TO 0

FOR EACH journey, counting from 1
    IF zones is 1 THEN
        SET fare TO 300
    ELSE IF zones is 2 THEN
        SET fare TO 450
    ELSE
        SET fare TO 600
    IF rider is student THEN
        SET fare TO half of fare
    IF spent is at least cap THEN
        SET charge TO 0
    ELSE
        SET charge TO fare
    ADD charge TO spent
    OUTPUT journey number, zones, fare and charge

OUTPUT spent as the day's total

A few choices here are worth noticing. All the input checks happen before anything is charged, so a bad entry never produces half a receipt. spent starts at 0 outside the loop, because it must carry over from one journey to the next. And each line does one thing: if a line needs "and then" in the middle, split it.

Check it worked

Find each rule from Step 1 in your steps. The zone prices appear in the IF zones is 1 block, the student discount in SET fare TO half of fare, the cap in the IF spent is at least cap block and the zone check near the top. Every IF has its lines indented under it, and every value used (cap, spent, fare, charge) is set before it is first used.

Step 3 · Trace the plan by hand

A plan can be tested before any code exists. Pick a sample day, then follow the steps line by line, writing every value down in a table. This is called a trace, or dry run.

Take an adult who makes three journeys: 3 zones, 3 zones, then 2 zones. The cap is 1000.

Text
journey  zones  fare  spent before  spent at least cap?  charge  spent after
1        3      600   0             no                   600     600
2        3      600   600           no                   600     1200
3        2      450   1200          yes                  0       1200

total today: 1200

Look at the total. The rules say nobody pays more than 1000 in a day, and this rider paid 1200. The plan followed its own steps correctly; the steps are wrong.

The gap is a question the plan never answered: what happens when the cap is reached partway through a fare? Before journey 2 the rider has paid 600, which is under the cap, so the plan charges the full 600, which takes them over it.

Check it worked

Your table matches the one above, row for row, and you can point to the exact line of pseudocode that let the total pass 1000: SET charge TO fare in journey 2.

Step 4 · Fix the plan, not the code

There are two possible answers to the question. Either the journey that crosses the cap is charged in full (and the cap only means later journeys are free), or it is charged only what is left before the cap. The rule as written, "nobody pays more than the daily cap", only fits the second one.

On a real project you would not guess. You would take the trace table to whoever owns the rule (the transport operator here) and ask. A trace table is a good way to ask, because it shows the exact case instead of describing it. Here, take the second answer: charge only what is left.

Replace the four cap lines in your plan:

Text
    IF spent is at least cap THEN
        SET charge TO 0
    ELSE
        SET charge TO fare

with one line:

Text
    SET charge TO the smaller of fare and (cap minus spent)

When the rider has paid nothing, cap minus spent is the whole cap, so they pay the full fare. Near the cap it is the amount left, and once the cap is reached it is 0, so the old "charge 0" case is still covered without a separate IF.

Trace the same day again, and two more, with the fixed plan:

Text
Day A: adult, journeys 3 3 2, cap 1000
journey  zones  fare  cap minus spent  charge  spent after
1        3      600   1000             600     600
2        3      600   400              400     1000
3        2      450   0                0       1000
total today: 1000

Day B: student, journeys 1 2 3 3, cap 500
journey  zones  fare  cap minus spent  charge  spent after
1        1      150   500              150     150
2        2      225   350              225     375
3        3      300   125              125     500
4        3      300   0                0       500
total today: 500

Day C: adult, journeys 1 1, cap 1000
journey  zones  fare  cap minus spent  charge  spent after
1        1      300   1000             300     300
2        1      300   700              300     600
total today: 600

Day C matters as much as the other two: it shows the fix did not break the ordinary case where the cap is never reached.

Check it worked

Your three tables match the ones above. No total is above its cap, Day C still charges the full fare twice, and your plan now has one SET charge line instead of the four-line IF.

Step 5 · Draw the plan as a flowchart

A flowchart shows the same plan as shapes and arrows, which makes loops and dead ends easy to see. Use rounded shapes for start and end, rectangles for actions and diamonds for yes-or-no questions. Draw the fixed plan on paper:

Flowchart of the bus-fare calculator. A rounded Start box reads rider type and journeys. A diamond asks whether rider and zones are valid; No leads right to Stop with a usage message. Yes leads down to a box that sets cap to 1000, or 500 for a student, and spent to 0. A diamond asks Another journey left?; No leads right to Output spent as the total and then End. Yes leads down to a box that sets the fare from the zones, then a diamond asks Student?; Yes leads right to fare equals half of fare, which rejoins below. Next comes charge equals the smaller of fare and cap minus spent, then spent equals spent plus charge and output the journey. An arrow on the left loops back up to the Another journey left? diamond.
The fixed plan as a flowchart. The loop returns to the question, not to the start.

Two things are easier to check here than in text:

  • Where the loop returns. The arrow after each journey goes back to "Another journey left?", not to the box that sets spent to 0. If it went back to that box, spent would reset every journey and the cap would never be reached. In pseudocode that bug would be one line indented in the wrong place; in a flowchart it is an arrow pointing at the wrong shape.
  • Every way out. Each diamond has exactly two exits, Yes and No, and every path ends at a rounded box.

You do not need both a flowchart and pseudocode for every program. Pseudocode is quicker for long, mostly straight plans; flowcharts are clearer when there are several decisions and loops, and when you are explaining a plan to someone who does not read code.

Check it worked

Your flowchart has three diamonds, each with two labelled exits. Follow it with your finger for Day A from Step 4: you go round the loop three times, and the total you reach is 1000.

Step 6 · Translate the plan into Python line by line

Now the code. Each pseudocode line becomes one or two lines of Python, and the pseudocode stays in the file as comments, so anyone reading the code can see the plan it came from.

Two columns. On the left, pseudocode lines: SET cap TO 1000; IF rider is student THEN SET cap TO 500; SET spent TO 0; FOR EACH journey, counting from 1; IF zones is 1 THEN SET fare TO 300; SET fare TO half of fare; SET charge TO the smaller of fare and (cap minus spent); ADD charge TO spent; OUTPUT spent as the day's total. On the right, the matching Python line for each one, such as charge = min(fare, cap - spent).
Each plan line maps to a line you can find in the script.

Check your Python version, make a folder for this tutorial and save the script:

Bash
python3 --version
mkdir -p ~/pseudocode-demo
cd ~/pseudocode-demo
cat > fares.py <<'PY'
import sys

# INPUT rider type and the list of journeys
# IF rider type is not adult or student, or there are no journeys THEN STOP
if len(sys.argv) < 3 or sys.argv[1] not in ("adult", "student"):
    sys.exit("usage: python3 fares.py adult|student ZONES [ZONES ...]")
rider = sys.argv[1]
journeys = sys.argv[2:]

# FOR EACH journey: IF zones is not a whole number of 1 or more THEN STOP
for text in journeys:
    if not text.isdecimal() or int(text) < 1:
        sys.exit(f"zones must be a whole number of 1 or more, got {text!r}")

# SET cap TO 1000, or 500 for a student
cap = 1000
if rider == "student":
    cap = 500

# SET spent TO 0
spent = 0

# FOR EACH journey, counting from 1
for number, text in enumerate(journeys, start=1):
    zones = int(text)

    # SET fare from the zone prices
    if zones == 1:
        fare = 300
    elif zones == 2:
        fare = 450
    else:
        fare = 600

    # IF rider is student THEN SET fare TO half of fare
    if rider == "student":
        fare = fare // 2

    # SET charge TO the smaller of fare and (cap minus spent)
    charge = min(fare, cap - spent)

    # ADD charge TO spent
    spent = spent + charge

    # OUTPUT journey number, zones, fare and charge
    print(f"journey {number}: zones {zones}, fare {fare}, charged {charge}")

# OUTPUT spent as the day's total
print(f"total today: {spent}")
PY
python3 fares.py adult 3 3 2

How each part of the plan became Python:

  • INPUT became sys.argv, the list of words typed after python3 on the command line. sys.argv[0] is the script name, sys.argv[1] is the rider type and sys.argv[2:] is everything after it: the journeys, as text.
  • STOP with a message became sys.exit("..."), which prints the message and ends the program with exit status 1, the usual signal that something went wrong.
  • "a whole number of 1 or more" became text.isdecimal() (every character is a digit, so "two" and "-1" fail) and int(text) < 1 (rejects 0). isdecimal() also accepts digits from other scripts, such as the Arabic-Indic ٣, and int() turns them into the same number, so the check works for riders who type in another script.
  • SET name TO value became name = value, and IF ... THEN / ELSE IF / ELSE became if / elif / else, with the same indentation as the plan.
  • FOR EACH journey, counting from 1 became for number, text in enumerate(journeys, start=1). enumerate hands back each item with a counter, and start=1 makes the first journey number 1 instead of 0.
  • half of fare became fare // 2, whole-number division, so the student fare stays a whole number (all the fares here are even).
  • the smaller of fare and (cap minus spent) became min(fare, cap - spent), almost word for word.
  • OUTPUT became print. The f before the quotes makes it an f-string, which puts the value of each name in {} into the text.

Check it worked

The output is the same as Day A in your hand trace:

Text
journey 1: zones 3, fare 600, charged 600
journey 2: zones 3, fare 600, charged 400
journey 3: zones 2, fare 450, charged 0
total today: 1000

Step 7 · Check the code against your trace tables

Your trace tables from Step 4 are now a test. Run the other two days and the inputs the plan says to reject:

Bash
cd ~/pseudocode-demo
python3 fares.py student 1 2 3 3
python3 fares.py adult 1 1
python3 fares.py adult 0 || echo "exit status $?"
python3 fares.py adult two || echo "exit status $?"
python3 fares.py child 1 || echo "exit status $?"

The || echo "exit status $?" part runs only when the command before it fails, and prints its exit status, so you can see the program stopped on purpose.

If a number in the output does not match your table, decide which one is wrong before you change anything. If the code does not do what the plan says, fix the code. If the plan itself was wrong, fix the plan first, re-trace it, and then change the code to match. That order keeps the plan, the flowchart and the code telling the same story.

Check it worked

The student day ends with journey 3: zones 3, fare 300, charged 125, journey 4: zones 3, fare 300, charged 0 and total today: 500. The adult day charges 300 twice and ends with total today: 600. The three bad inputs each print a message and exit status 1: two start zones must be a whole number of 1 or more, with '0' and 'two' at the end, and the child one prints the usage line.

When you have finished, delete the demo folder. Keep your paper plan and flowchart; they are the documentation for fares.py.

Bash
cd ~
rm -rf ~/pseudocode-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.