English:Programming fundamentals in Python - Computing Year 10
Introduction

Design, write and test complete Python programs. Follow a worked fare calculation, then build a validated discount tool with clear input conversion, selection, finite iteration, readable output and actual test evidence. The examples use invented educational prices and synthetic inputs.
Connect a specification with Python data and control
Express a specification in a textual language
A high-level language such as Python provides readable constructs for variables, functions, decisions and repetition. A program still needs translation/execution support from a language implementation; the processor does not directly understand arbitrary English or every Python statement. Assembly is a lower-level notation closely related to an instruction set, and machine instructions are a different representation again. “High-level” does not mean automatically correct, secure or suitable for every task.
For our original fare example, a fictional service charges £0.40 per kilometre for the first 20 km and £0.30 per additional kilometre beyond 20. Distance must be finite and between 0 and 1000 km inclusive. The lower rate applies only to the extra distance, not retrospectively to the whole journey. There is no booking charge, tax, live tariff lookup or real payment. State this specification before selecting operators or drawing an interface.
Follow input, conversion, processing and output
Python input returns text. A user entering 12.5 supplies a string until a conversion such as float turns it into a numeric value. Do not multiply the text itself and expect a fare calculation. Strings are appropriate for labels; a numeric type is appropriate for arithmetic; a Boolean is useful for a condition such as whether the value is in range. Choose meaningful names such as distance_km rather than unrelated letters that hide the units.
| Stage | Worked value or responsibility |
|---|---|
| Input | Text "12.5" |
| Conversion | Numeric distance 12.5 km |
| Validation | Finite and within 0 through 1000 |
| Selection | The distance lies in the first 20 km band |
| Processing | 12.5 ×0.40 =5.0 |
| Output | Display 5.00 GBP with two decimal places |
For 25 km, the first 20 km cost 8.00 and the extra 5 km cost 1.50, giving 9.50. Charging 25 ×0.30 would produce 7.50 and implement the wrong rule. For 0 km, the stated model gives 0.00; a zero input is not automatically missing or invalid. A real service might use a different contract, so the invented example must never be presented as a current quote.
Read sequence, selection and iteration
Sequence orders conversion before calculation and output. Selection uses if/else to choose the appropriate calculation. Iteration runs the same calculation over a finite list of example inputs. Indentation groups the statements controlled by a function, branch, loop or exception handler; changing indentation can change behaviour even when every individual line looks plausible. A colon starts these suites in the examples.
An assignment binds a value to a name; an equality comparison asks a question. A function parameter receives an input, and return passes a result to the caller. Printing displays text; it does not replace the returned value or save a permanent record by itself. These distinctions matter when you test a calculation separately from its interface.
Corey Schafer: Integers and Floats. Compare numeric operations and display with the original fare trace. A floating-point value can approximate a decimal; a printed two-decimal result does not prove every internal value is an exact currency amount. Original: Corey Schafer, Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data. The written explanations and native tasks work without sound or the external player.
Plan tests before trusting a result
Write expected results by hand before running the program. Include 12.5 km→5.00, exactly 20 km→8.00,25 km→9.50 and 0 km→0.00. Then add negative, above-limit, missing and nonnumeric inputs. A program that starts without a syntax error can still implement the wrong rate, accept a nonfinite value or display unlabelled output. The specification is the reference, not whether the terminal looks busy.
Run trace and debug a complete fare program
Run the complete fare program
Run this complete program in an approved Python 3 environment with a terminal that supports input. It imports only the standard math module and accesses no network, real customer records, payment system or files. It prints four finite worked examples, asks once for one distance and either displays a result or an input error. There is no unbounded retry loop.
import math
def fare_for_distance(text):
if type(text) is not str or len(text) > 40:
raise ValueError("Enter distance as short numeric text")
try:
distance_km = float(text)
except ValueError as error:
raise ValueError("Distance must be numeric") from error
if not math.isfinite(distance_km) or not 0 <= distance_km <= 1000:
raise ValueError("Distance must be finite and from 0 to 1000 km")
if distance_km <= 20:
total = distance_km * 0.40
else:
total = 20 * 0.40 + (distance_km - 20) * 0.30
return total
if __name__ == "__main__":
for example in ["0", "12.5", "20", "25"]:
print(example, "km ->", format(fare_for_distance(example), ".2f"), "GBP")
try:
entered = input("Distance in km: ")
print("Illustrative fare:", format(fare_for_distance(entered), ".2f"), "GBP")
except ValueError as error:
print("Input error:", error)The worked example list prints 0.00,5.00,8.00 and 9.50 GBP for 0,12.5,20 and 25 km. Entering 12.5 at the prompt displays Illustrative fare:5.00 GBP. The format specification .2 f controls presentation to two decimal places; it does not change a float into an exact decimal monetary model. Rates and outputs remain educational illustrations rather than a billing implementation.
Validate conversion and meaning separately
float can parse several forms of numeric text, including surrounding whitespace and scientific notation. It can also produce infinity or NaN for certain text; those are not acceptable journey distances. The explicit finite/range check rejects them, negative values and values above 1000. An input such as "twelve" fails conversion and is reported clearly rather than treated as zero. A short-text limit keeps this classroom interface bounded.
The function expects text because it models an input prompt. Passing a list, a Boolean or a numeric object directly is outside this interface. Zero after conversion is valid under this specification. Validation is not the same as a promise that an entered distance is accurate in the physical world; no journey was measured by the program.
Debug by identifying the first mismatch
Consider a faulty design that multiplies every distance by 0.40. It gives the correct 5.00 at 12.5 km but the wrong 10.00 at 25 km. The first-band test alone would miss that defect. A second faulty design charges the whole 25 km at 0.30 and returns 7.50. Trace the 20 km allowance and the 5 km remainder to show why 9.50 is required.
Use an expected/actual table with input, expected result, observed result, pass/fail and a short reason. Preserve a failed test before revising the code. Correct the rate selection or extra-distance formula, then rerun both bands and the boundary. Do not alter the expected answer merely to fit the defect. A syntax error, a runtime conversion error and a logic error need different explanations.
Keep text and numeric data distinct
The text "80" is a sequence of characters. Converting it to an appropriate numeric representation allows arithmetic, but concatenating it with a label is still a text operation. Print and format produce readable output. They do not prove that the underlying rule was correct. Do not evaluate arbitrary input as Python code; use the explicit numeric conversions and validation shown here.
If the school editor has no interactive input console, run the function with supplied strings in an approved environment or complete the trace on paper. Mark paper reasoning as unexecuted practical work. The author’s tested sample is not evidence that a learner has run their own program or repaired their own defect.
Build and test a precise discount application
Transfer the method to a discount program
The required independent task reads an item price and a discount percentage, validates them and prints the discounted price with two decimal places. This original contract uses GBP, a finite price from 0 through 1,000,000 and a finite percentage from 0 through 100 inclusive. Both inputs may contain at most two decimal places. Negative prices, nonfinite values, missing/nonnumeric text and out-of-range percentages are rejected. These are teaching limits, not a real shop’s terms.
For price 80 and discount 15%, the discount fraction is 15 ÷100 =0.15. The retained fraction is 1−0.15 =0.85, so the result is 80 ×0.85 =68.00. At 0% the price stays 80.00; at 100% it becomes 0.00. Multiplying by 0.15 gives the discount amount 12.00, not the discounted price. Decide which output is required before writing the formula.
Use an explicit decimal and rounding policy
The transfer uses Python’s standard decimal module and constructs Decimal values directly from input text. The two-place input rule bounds precision for this small exercise. The final result is rounded to the nearest penny using ROUND_HALF_UP: a positive exact half-penny goes upward. Other systems can choose different rounding rules; state the rule rather than assuming that every Python or spreadsheet operation uses it.
For price 0.05 with 10%off, the unrounded result is 0.045. Under our explicit half-up policy it becomes 0.05. This example exposes a rounding boundary. Decimal arithmetic supports exact decimal inputs here, but it does not guarantee that every possible operation has infinite precision or that this demonstration is a complete accounting system. Check the actual contract and environment when extending a program.
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
def decimal_input(text, label, maximum):
if type(text) is not str or len(text) > 40:
raise ValueError(label + " must be short numeric text")
try:
value = Decimal(text)
except InvalidOperation as error:
raise ValueError(label + " must be numeric") from error
if not value.is_finite() or not Decimal("0") <= value <= maximum:
raise ValueError(label + " is outside the finite allowed range")
if value != value.quantize(Decimal("0.01")):
raise ValueError(label + " may have at most two decimal places")
return value
def discounted_price(price_text, percent_text):
price = decimal_input(price_text, "Price", Decimal("1000000"))
percent = decimal_input(percent_text, "Discount", Decimal("100"))
result = price * (Decimal("1") - percent / Decimal("100"))
return result.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
if __name__ == "__main__":
for percent in ["0", "15", "100"]:
print("80 GBP with", percent, "percent off ->", format(discounted_price("80", percent), ".2f"), "GBP")
try:
price_text = input("Price in GBP: ")
percent_text = input("Discount percent: ")
print("Discounted price:", format(discounted_price(price_text, percent_text), ".2f"), "GBP")
except ValueError as error:
print("Input error:", error)The three built-in examples show 80.00,68.00 and 0.00 GBP. Enter 80 and 15 at the prompts to reproduce 68.00. decimal_input is reused for the price and percentage with different maximum values. discounted_price returns a Decimal result; the interface formats it for display. All processing remains local and uses synthetic inputs rather than real customer or payment information.
Test, refine and explain the program
| Input case | Expected result | Purpose |
|---|---|---|
| Price 80; discount 15 | 68.00 GBP | Normal required transfer |
| Price 80; discount 0 | 80.00 GBP | Inclusive lower percentage boundary |
| Price 80; discount 100 | 0.00 GBP | Inclusive upper percentage boundary |
| Price 0; discount 15 | 0.00 GBP | Valid zero price |
| Price 0.05; discount 10 | 0.05 GBP | Explicit half-penny rounding policy |
| Negative price or discount 101 | Input error | Invalid range |
| NaN, Infinity, blank or nonnumeric input | Input error | Nonfinite or conversion failure |
| Price 1.001 or discount 15.001 | Input error | Declared two-decimal input precision |
Run normal, boundary and invalid cases and keep actual output. One useful refinement is replacing a vague “invalid” message with a label-specific correction prompt while keeping the validation rules unchanged. Another is correcting a formula that returns the discount amount instead of the retained price. Record the initial defect or usability issue, the change and the affected retests. Do not invent a user study or claim a revision you did not perform.
Evaluate fundamentals and next steps
Explain a meaningful variable, a conversion, a branch, a finite loop, a function parameter and a return value. Compare the floating-point fare demonstration with the explicitly rounded decimal transfer. Identify an assumption, one remaining limitation and one further test. Keep syntax, runtime errors, logic and display concerns distinct.
Submit complete runnable source, the specification, hand calculations, actual expected/observed tests and a reasoned refinement. These tasks support the mapped GCSE/KS 4 pathway; Year 10 allocation is editorial and a chosen awarding organisation may specify particular conventions. A quiz score or copied code is not proof of the learner’s own practical execution, complete qualification or permission to build a live payment system.
Interactive Tasks
Quiz: Test Your Knowledge
What does Python input return before conversion? (Text as a string) (!An automatically validated decimal price) (!A machine instruction) (!A saved payment receipt)
What is the illustrative fare for 12.5 km in the first band? (5.00 GBP) (!12.50 GBP) (!0.40 GBP) (!3.75 GBP)
What is the illustrative fare for 25 km under the stated two-band rule? (9.50 GBP) (!7.50 GBP) (!10.00 GBP) (!8.00 GBP)
What purpose does the finite check serve? (Reject infinity and NaN as journey distances) (!Make every entered distance physically accurate) (!Save a permanent report automatically) (!Convert every string into executable code)
What does indentation do in these Python programs? (Group statements belonging to functions branches loops and handlers) (!Decorate the source without affecting behaviour) (!Set every variable’s currency) (!Remove all runtime errors)
What is the discounted price for 80 GBP with 15 percent off? (68.00 GBP) (!12.00 GBP) (!95.00 GBP) (!65.00 GBP)
Which boundary interpretation is correct? (Both 0 and 100 percent are accepted) (!Zero percent is always missing input) (!100 percent must always increase the price) (!Negative discounts are accepted silently)
What is the result for 0.05 GBP with 10 percent off under the stated half-up policy? (0.05 GBP) (!0.04 GBP) (!0.045 GBP displayed as a final penny amount) (!0.50 GBP)
Which statement about two-decimal formatting is correct? (It controls display and does not alone prove exact internal currency arithmetic) (!It proves every branch was tested) (!It converts every float into a legal payment) (!It removes the need to state a rounding rule)
What is the strongest practical evidence here? (Complete source with actual expected-versus-observed tests and a recorded refinement) (!Only a screenshot of unexecuted code) (!A claim that a running program must meet any specification) (!An unlabelled final number with no input)
Memory Game
| String | Textual data such as a prompt or unconverted input |
| Conversion | Changing an input representation into an appropriate numeric type |
| Selection | Choosing a branch using a condition |
| Iteration | Repeating a finite set of example calculations here |
| Parameter | A named input received by a function |
| Return value | A result passed from a function to its caller |
Drag and Drop
| Specification first | State the fare bands units range and required output |
| Input validation | Reject invalid nonfinite or out-of-range values |
| Rate selection | Charge the first 20 km separately from additional distance |
| Discount calculation | Multiply price by the retained fraction after the percentage reduction |
| Test and refine | Compare actual results with prior expectations then retest the revision |
Crossword Puzzle
| PYTHON | Which textual high-level language is used here? |
| STRING | What type holds text before conversion? |
| PARAMETER | What named input does a function receive? |
| DECIMAL | Which standard module supports the transfer’s decimal calculation? |
| INDENTATION | What groups Python statements into suites? |
| VALIDATION | What checks values against the input contract? |
LearningApps
Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.
Cloze Text
Open Tasks
Easy
- Trace the fare example: Follow input text, conversion, validation, branch, calculation and labelled output for 12.5 km.
- Identify the constructs: Find sequence, selection, a finite loop, parameter and return value in the code.
- Distinguish types and display: Compare strings, floats, Decimal results and two-place formatted text.
- Explain zero cases: Show why 0 km and 0 percent are valid under the stated contracts.
Standard
- Complete the required discount program: Read and validate price and percentage, then reproduce 80 GBP with 15 percent off as 68.00.
- Record normal boundary and invalid tests: Include 0 and 100 percent, negative price, above-limit percentage, nonnumeric and nonfinite text.
- Debug the two fare defects: Explain why multiplying all 25 km by 0.40 or all 25 km by 0.30 fails the stated rule.
- Refine an error message: Preserve the first version, improve a label-specific correction message and record affected retests.
Advanced
- Defend the rounding rule: Explain the 0.05 GBP/10 percent case and compare it with an alternative explicitly stated policy.
- Separate interface and calculation: Show how returned values can be tested independently of prompts and printed labels.
- Evaluate an extension: State new requirements before adding another rate, discount policy or input precision.
- Defend a practical portfolio: Submit source, manual expectations, actual outputs, a revision and honest limitations without claiming live financial approval.
Learning Check
- Worked fare and selection: Trace 12.5 km and 25 km under the stated tariff.
- Required discount transfer: Calculate 80 GBP less 15 percent and the boundary percentages.
- Conversion and invalid input: Explain why conversion alone is insufficient.
- Decimal rounding policy: Explain the half-penny example and display distinction.
- Testing and refinement: Show how a normal passing case can hide a defect.
- Practical scope and language level: Describe a defensible final submission.
Worked checks and assessment guidance
- Input text 12.5 converts to a finite float in range, uses the first band and gives 12.5×0.40=5.00 GBP. At 25 km, the first 20 cost 8.00 and the remaining 5 cost 1.50, total 9.50. Applying the lower rate to the whole journey or ignoring the lower additional rate implements a different rule.
- The retained fraction is 1−15/100=0.85, so 80×0.85=68.00. The discount amount alone is 12.00, not the required retained price. At 0 percent the result is 80.00; at 100 percent it is 0.00. Price 0 is accepted and stays 0.00 under this teaching contract.
- A numeric-looking input still needs range and finiteness checks. The programs reject blank/nonnumeric input, NaN, infinity, negative values and values beyond their limits. The discount also enforces at most two decimal places. Error handling reports the issue without evaluating arbitrary text as code or silently replacing it by zero.
- Decimal input 0.05 with 10 percent off yields exact unrounded 0.045 in this bounded calculation. The explicit positive half-up rule rounds it to 0.05. Formatting to two places controls displayed text; it does not alone make a float exact or establish a complete accounting system. Other policies need their own stated expectations.
- Charging every kilometre at 0.40 passes 12.5 km but produces 10.00 at 25 instead of 9.50. Charging all 25 at 0.30 gives 7.50. Preserve expected/actual records, correct the branch or extra-distance formula, and rerun both bands, boundaries and invalid cases. Refine one actual defect or usability issue without inventing a user study.
- Keep specification, complete source, manual traces, actual test outputs, environment and a reasoned refinement. Python is a high-level textual language supported by an execution implementation; lower-level representations differ. The programs have finite example loops and local synthetic inputs, no live payment or customer access. Paper prediction and copied examples are not the learner’s own executed evidence or a qualification.
Learning evidence
Keep the exact invented specification,complete fare and discount source,manual calculations,actual normal/boundary/invalid test records and one reasoned refinement. Explain input conversion,units,selection,finite iteration,return values and rounding. Mark paper traces separately from execution;no real payment,customer-data processing,financial approval or qualification is established.
OER and Wikipedia
Python built-in functions for input, conversion and display; Python math for the finite-value check; Python decimal for text-based decimal arithmetic, quantization and explicit ROUND_HALF_UP. Original complete programs and synthetic test cases were actually executed during author review. DfE GCSE Computer Science subject content is the mapped common baseline, with editorial Year 10 allocation and school/awarding-organisation practical requirements. Primary technical references reviewed 14 November 2026.
Python Code.jpg, Weal2019, CC0. Unchanged original; caption and learning activities are original.
Corey Schafer: Python Tutorial for Beginners 2: Strings - Working with Textual Data; unchanged original publisher embed, not a partnership or a re-upload licence.
Corey Schafer: Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data; unchanged original publisher embed; original media research and preview hashes retained.
Linked learning areas
aiMOOC Projects
Schulfach+


aiMOOCs


aiMOOC Projekte


NEWSLernweltNOAH fragen