──────────────────────────────────────

8. Make Code You Can Trust · Build a Tested Fare Estimator

Use a clear function contract and handle a bad request at the boundary.

Lesson files · lessons/design-and-testing/fares-tool

Before you start
- Return a calculation from a function.
- Catch a ValueError from int().
- Check a calculation with assertions.

By the end
- Calculate the fare for a positive distance and for zero.
- Reject negative or malformed distances with the requested message.
- Check the fare rule with two assertions in the same program.

Where you can use it
Give a club treasurer a trip estimator that quotes a fare for zero kilometres and tells them how to fix invalid entries.

Use whole rand for this small model. The policy is a base charge of 8 and 3 per kilometre, with zero kilometres a valid value. Negative distances are invalid. Treat missing or bad values as input problems and keep the fare calculation separate.

Predict
What is the expected fare for zero kilometres?
- 0
- 8

Worked example (example.py)

def fare(km: int) -> int:
    return 8 + km * 3

assert fare(0) == 8
print(fare(2))


Example result
14

Read one distance. Print Fare: R followed by the result for non-negative integers, or Enter a non-negative whole number. for negative or invalid input. Include assertions for 2 and 0.

Starter program (starter.py)

def fare(km: int) -> int:
    return 8 + km * 3

assert fare(0) == 8
print(fare(2))


Hint
Fail negative values before calling fare. Use a narrow ValueError handler around the conversion or range validator.

Case 1. Try the sample
Input
2
Expected output
Fare: R14

Case 2. Minimum valid distance
Input
0
Expected output
Fare: R8

Case 3. Invalid input
Input
two
Expected output
Enter a non-negative whole number.

Project checklist
Run the sample case.

Project checklist
Try one different case and explain what happened.

Marking criterion
Program behaviour (4 points)
Each required behaviour works on the supplied cases.

Marking criterion
Use of the lesson concept (3 points)
The code uses the main idea in a clear, purposeful way.

Marking criterion
Test evidence (2 points)
The reflection describes a case, its expected result and what happened.

Marking criterion
Explanation (1 points)
The learner explains a change or design decision in their own words.

Stretch
Accept a second parameter for passenger count and write boundary tests for it.

Reflect
What would change in your tests if rides started at R10?

Check your prediction
8 The fixed base charge still applies.
