Zum Inhalt springen

English:Procedures, functions and modular Python programs - Computing Year 8

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

Procedures, functions and modular Python programs - Computing Year 8

QR-Code



Introduction

Python source code as programming context
Weal2019’s unchanged photograph shows an unrelated Python program. The original functions and actual tests below, rather than the photographed matrix code, are the course implementation.

Build reusable Python functions with clear inputs, returns and tests. Turn repeated calculations into independently testable components and combine them in a small original report. Year 8 placement is editorial within England’s KS3 Computing pathway.


Follow function calls, arguments and return values

A function gives a named task a reusable interface. Rather than repeating the same rectangle calculation in several places, define how to obtain the area from two dimensions. The parameters are the names in the definition; the arguments are the actual values supplied by a call. In this first example dimensions are assumed to be valid numbers in the same unit. Validation is added explicitly in the next chapter, rather than being implied by the function's name.

def area_rectangle(width, height):
    return width * height

answer = area_rectangle(4, 6)
print(answer)

The definition starts with def, followed by a name, parameter list and colon. The indented body belongs to the function. Defining this simple function creates the function; it does not perform its multiplication at that moment. The later call supplies four and six, runs the body and returns twenty-four. Assignment stores that returned value in answer. Printing answer displays the result, but the multiplication could equally be used in another calculation without printing it.

Stage What happens Meaning
Caller Evaluate area_rectangle with arguments 4 and 6 Waiting for result
Function body Bind width to 4 and height to 6 Local parameter names
Expression Multiply 4 by 6 24
Return Send 24 back to the caller This invocation ends
Caller resumes Assign returned 24 to answer Printing is a separate action
Rectangle with side labels a and b and area a times b
This unchanged Commons diagram shows the mathematical relationship. Our calls use width and height in centimetres and return area in square centimetres; the drawn rectangle is not a measured four-by-six photograph.

The function interface hides a small implementation detail: callers need to know the input meanings and the returned meaning, not repeat the multiplication every time. That is a useful computational abstraction. It does not hide the assumptions from documentation or testing. A clear contract states accepted inputs, units, output and failure behaviour. Choosing a meaningful name is helpful, but a name alone cannot enforce the contract.

Separate return from print. The following different function displays a calculation but contains no explicit return statement. After printing twenty-four, it finishes and implicitly returns None. The final print therefore displays None, not another twenty-four. A function used for a display action is often called a procedure in introductory discussions; Python still represents it as a function and it returns None. None is not the integer zero or the text 'None'.

def show_area(width, height):
    print(width * height)

result = show_area(4, 6)
print(result)

Before running either example, predict each output line and label where the result becomes available to the caller. Do not treat seeing a number on screen as proof that a useful value was returned. A later expression expecting a number cannot correctly use None as the rectangle's area. Adding a return statement is a change to the interface, not a reason to claim the original print-only function returned twenty-four all along.

Corey Schafer's original Python functions tutorial supplies a moving-code explanation of definitions, arguments and returns. Focus first on those concepts; optional later examples go beyond this introductory contract. The complete original teaching, code and tests here remain available without external playback. Original: Corey Schafer, Python Tutorial for Beginners 8: Functions. The written explanations and native tasks work without sound or the external player. Use a paper call trace if a local editor is unavailable. Mark predictions as predictions. Practical evidence requires running the supplied or independently written code in an approved Python environment and recording actual results; a screenshot of unrelated code is not that evidence.



Separate validation, measurements and duration conversion

Modularity separates responsibilities that can be tested independently. Our original miniature report combines rectangle measurements and a duration. It is a learning model, not a building specification, time-sheet service or real booking. To make its behaviour precise, accept dimensions as whole centimetres from zero through one hundred inclusive and duration as whole minutes from zero through one thousand four hundred and forty inclusive. These limits are invented interface rules, not mathematical limits on rectangles or time.

Start with one small validation function. It returns an accepted value unchanged and raises ValueError otherwise. The exact type check deliberately rejects Boolean values even though Python treats bool as an integer subtype in some operations. Reject decimal numbers and numeric text too: this interface expects an already parsed integer. A future text-entry layer may convert input, but it must not silently alter this contract.

def check_dimension(value):
    if type(value) is not int or not (value >= 0 and 100 >= value):
        raise ValueError("Use whole centimetres from 0 to 100")
    return value

def rectangle_measures(width, height):
    width = check_dimension(width)
    height = check_dimension(height)
    area = width * height
    perimeter = 2 * (width + height)
    return area, perimeter

The rectangle function calls the shared validator for both inputs, computes two different quantities and returns a tuple in a stated order: area first, perimeter second. For four and six the area is twenty-four square centimetres and the perimeter twenty centimetres. Swapping width and height preserves both outputs. Equal numerical outputs in an occasional example would not make their units interchangeable.

Zero dimensions are allowed by the stated computational contract. For zero and six the returned pair is zero square centimetres and twelve centimetres. This is the formula applied to a degenerate model, not a claim about a useful physical rectangle with a positive enclosed area. If a real application requires strictly positive dimensions, change its acceptance rule and tests explicitly. Do not quietly replace the announced zero boundary.

def split_minutes(total_minutes):
    if type(total_minutes) is not int or not (total_minutes >= 0 and 1440 >= total_minutes):
        raise ValueError("Use whole minutes from 0 to 1440")
    hours = total_minutes // 60
    remaining_minutes = total_minutes % 60
    return hours, remaining_minutes

The duration function uses whole-number division and remainder. With one hundred and thirty-five minutes, two complete groups of sixty leave fifteen minutes, so it returns the tuple two, fifteen. With fifty-nine it returns zero, fifty-nine; with sixty it returns one, zero. With one thousand four hundred and forty it returns twenty-four, zero. This is a duration, not a clock time that must wrap to midnight. A remainder is always from zero through fifty-nine for these nonnegative inputs.

Flowchart illustrating input, calculation and output
Dave Braunschweig’s unchanged Flowgorithm diagram converts Fahrenheit to Celsius. It illustrates separating input, processing and output; it is not the call graph or implementation of our rectangle-and-duration functions.

Parameter names belong to each call's local scope. The width name inside rectangle_measures does not overwrite an unrelated width name in the caller merely because the spelling matches. These functions receive immutable integers, use local names and return new results; they do not edit a shared list or global learner record. That qualified claim concerns this implementation, not every possible function: a different function could mutate a list or explicitly use global state.

Each function has one responsibility, but there is no universal rule that every line needs a new function. A useful boundary makes a task meaningful, reusable and independently testable. Splitting code into confusing fragments or duplicating the same validation rule in many places would weaken that benefit. Explain the interface and a concrete test whenever proposing a new component.



Compose modules and test their contracts

Combine tested components, then test the combination. The report function calls the measurement and duration functions, unpacks their returned pairs and constructs a fresh dictionary with explicit field names and units. It does not prompt, print, save, publish or send data. Keeping those actions outside the pure calculation makes expected and actual values easy to compare.

def make_report(width, height, total_minutes):
    area, perimeter = rectangle_measures(width, height)
    hours, minutes = split_minutes(total_minutes)
    return {
        "area_cm2": area,
        "perimeter_cm": perimeter,
        "hours": hours,
        "minutes": minutes,
    }

Calling make_report with four, six and one hundred and thirty-five returns area_cm2 twenty-four, perimeter_cm twenty, hours two and minutes fifteen. Follow the calls in order: validate the dimensions, calculate and return the measurement pair, validate and split the duration, then build the report. The intermediate pairs are real return values. They do not appear on screen unless a caller chooses to display them.

Use separate unit tests for each component and integration tests for the report. Independently calculate the expected area, perimeter and duration before running the program. For four by six, count four rows of six unit squares and add the four side lengths; for one hundred and thirty-five minutes, subtract two complete hours. Copying the exact implementation expression into every test can preserve the same mistake on both sides.

Test input Expected result Reason
rectangle_measures with 4 and 6 Area 24 and perimeter 20 Ordinary input and distinct units
rectangle_measures with 0 and 6 Area 0 and perimeter 12 Announced zero boundary
rectangle_measures with 100 and 100 Area 10000 and perimeter 400 Maximum permitted dimensions
split_minutes with 59, then 60 0 hours 59 minutes, then 1 hour 0 minutes The hour boundary
split_minutes with 1440 24 hours and 0 minutes Maximum duration, not a clock
A dimension of minus 1, 101, True or text 4 ValueError Range or exact-type rejection

The exact original functions were actually executed against every permitted dimension pair from zero to one hundred and every permitted duration from zero to one thousand four hundred and forty. Independent references counted unit-square rows and side lengths and checked the duration decomposition. Invalid types and out-of-range values, print-versus-return output, local scope and fresh report dictionaries were also checked. These are author checks, not evidence that every learner has executed the program or an independent professional certification.

Make at least two deliberate faulty variants on paper before correcting them: returning width plus height as area, returning height twice as perimeter, or printing the duration instead of returning it. Choose a discriminating example rather than relying only on one-by-one squares. Zero alone would fail to expose several wrong formulae. Record the first failed expectation, repair the relevant function and rerun both its unit tests and the composed report tests.

Corey Schafer: integer and float operations support the division and remainder discussion; these are separate from the original program's contract.

For transfer, replace the fictional report's dimension limit with two hundred while retaining whole centimetres. Update the validator, maximum-case tests and contract, then check callers. Separately add a seconds converter if useful; do not relabel minutes as seconds without changing the arithmetic. More than one programming language is a broader KS3 objective: this Python lesson contributes to modular programming but does not by itself establish the complete multi-language requirement.

Submit an actual runnable file with at least the measurement and duration functions, one composed caller, documented parameter and return meanings, and expected-versus-actual normal, zero, boundary and invalid tests. A paper call graph is a valuable accessible route for reasoning, clearly identified as a trace rather than an executed practical artefact.



Interactive Tasks


Quiz: Test Your Knowledge

What does the first area function return for width four and height six? (The number twenty-four) (!The text four followed by six) (!None because multiplication cannot be returned) (!Ten because the dimensions must always be added)



When does the multiplication in the simple area function run? (When the function is called) (!Whenever its definition line is first read) (!Only after the entire program has ended) (!When any unrelated variable is printed)



What are width and height in the definition? (Parameters that receive the supplied argument values) (!Global variables that every function must share) (!Output labels that cannot be used in expressions) (!Actual measured dimensions known before any call)



What does the print-only show_area function return? (None after displaying the calculated area) (!The area simply because it appeared on screen) (!The text twenty-four for every input) (!Zero because every procedure must return zero)



What does rectangle_measures return for four and six? (Area twenty-four square centimetres and perimeter twenty centimetres) (!Area twenty centimetres and perimeter twenty-four square centimetres) (!Area ten and perimeter twenty-four with no units) (!Only the displayed number twenty-four and no return value)



What is the duration result for one hundred and thirty-five minutes? (Two whole hours and fifteen remaining minutes) (!One hour and seventy-five remaining minutes) (!Two hours and thirty-five minutes) (!One hundred and thirty-five hours and zero minutes)



Why is True rejected as a dimension in the validated model? (The announced interface requires an exact integer type and rejects Boolean values) (!Python never permits Boolean values in any arithmetic) (!True means one hundred centimetres in every geometry program) (!Rejecting it proves every external user input is safe)



What does the model do with one thousand four hundred and forty minutes? (Return twenty-four hours and zero minutes as a duration) (!Wrap to zero and silently discard the full day) (!Reject it because twenty-four hours cannot be represented) (!Return fourteen hours and forty minutes)



Why test the composed report after its component functions pass? (Correct components can still be combined or labelled incorrectly) (!Component tests are never useful for any function) (!A dictionary automatically proves all its field units) (!Integration tests replace the need for any expected results)



What is required when changing the accepted dimension limit? (Revise the contract and affected tests as well as the validation rule) (!Change only the photograph while keeping every old expectation) (!Rename the report and assume its inputs are now correct) (!Overwrite the real learner record to prove that the program ran)





Memory Game

Parameter A name in a function definition
Argument A value supplied to a function call
Return value A result sent back to the caller
Local scope Names belonging to a particular function call
Unit test A focused check of one component
Integration test A check of components working together





Drag and Drop

A number is displayed but the caller receives None Distinguish print from return and inspect the interface
The same acceptance rule is copied into several calculations Use a meaningful shared validation function
A duration reaches exactly sixty minutes Return one whole hour and zero remaining minutes
A width of zero is supplied to the stated model Accept it and explain the degenerate measurement result
A caller labels perimeter as square centimetres Correct the integration and unit labels as well as checking calculations





Crossword Puzzle

FUNCTION What named reusable component can accept inputs and return a result?
PARAMETER What name appears in the definition to receive an input?
ARGUMENT What value is supplied by a caller?
RETURN What statement sends a result back from a function?
SCOPE What describes where a name is bound and accessible?
MODULAR What design separates clear reusable components?





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

Complete the explanation.
A function definition gives a task a

. Its input names are

. Values supplied in a call are

. A result goes back using

. Displaying output with print does not itself return the displayed

. The validated dimension interface uses whole

. Area has square-centimetre

. One hundred and thirty-five minutes splits into two hours and

minutes. A unit test checks one

. A composed report also needs an integration

.



Open Tasks


Easy

  1. Trace a call: Annotate the five call stages for area_rectangle with four and six.
  2. Predict two outputs: Compare the basic area program with the print-only version and explain None.
  3. Name interfaces: Identify parameters, arguments, return order and units for rectangle_measures.
  4. Split an hour boundary: Predict and explain the results for fifty-nine, sixty and sixty-one minutes.


Standard

  1. Refactor repetition: Replace three repeated rectangle calculations with calls to one documented function.
  2. Build the two components: Write measurement and duration functions with the stated contracts and a separate caller.
  3. Test zero and maximum: Calculate expected results for zero by six, one hundred by one hundred and duration one thousand four hundred and forty.
  4. Audit a report: Trace make_report with four, six and one hundred and thirty-five and label all four returned fields.


Advanced

  1. Find discriminating tests: Choose counterexamples for incorrect area, perimeter and print-only duration implementations.
  2. Extend a limit: Raise the fictional dimension maximum to two hundred and document all affected contracts and tests.
  3. Compare designs: Explain when a new helper improves testability and when fragmentation would make the program harder to understand.
  4. Provide practical evidence: Run the original or your equivalent program, record expected versus actual normal and invalid cases, and distinguish execution from paper predictions.



Learning Check

  1. Calls and return flow: Explain the original simple area example.
  2. Measurements and contracts: Calculate ordinary and zero cases with units.
  3. Duration conversion: Explain the transfer example and limits.
  4. Composition and scope: Explain the report and local values.
  5. Testing and debugging: Choose useful independent expected results.
  6. Evidence and transfer: Adapt the program without overstating achievement.


Worked checks and assessment guidance

  1. The definition creates the function without performing this multiplication. The call supplies arguments four and six to local parameters width and height, calculates twenty-four and returns it. The caller assigns that result to answer and then prints it. A print-only function displays twenty-four but implicitly returns None; the later print of its result therefore displays None.
  2. For four and six, area is four rows of six unit squares or twenty-four square centimetres; perimeter is four plus six plus four plus six or twenty centimetres. For zero and six, the announced computational contract returns zero and twelve, describing a degenerate model. A requirement for positive physical dimensions would need a different contract, rather than silently rejecting an allowed boundary.
  3. One hundred and thirty-five minutes contains two complete groups of sixty and fifteen remaining minutes, so split_minutes returns two and fifteen. Fifty-nine returns zero and fifty-nine; sixty returns one and zero; one thousand four hundred and forty returns twenty-four and zero. This is a duration, not a clock time. Minus one, above-limit values, Boolean values, strings and floats fail the specified exact-type or range contract.
  4. make_report calls the validated measurement and duration functions and places returned values into area_cm2, perimeter_cm, hours and minutes. For four, six and one hundred and thirty-five these are twenty-four, twenty, two and fifteen. The pure functions use local names and immutable integer inputs and return a fresh dictionary. That does not mean every possible Python function is incapable of changing shared state.
  5. Use unit tests for each function and integration tests for the labelled report. Count unit-square rows and four side lengths independently; check that sixty times hours plus the remainder reconstructs the duration and the remainder is from zero to fifty-nine. Test ordinary, zero, exact hour, maximum, invalid type and out-of-range cases. A one-by-one-only area test or a zero-only test can miss incorrect formulae; rerun affected component and report tests after repair.
  6. A changed dimension limit requires updated documentation, validator and maximum/beyond-maximum expectations. Separating display from returned calculations lets the same pure components support another interface. Submit at least two runnable functions, a composed caller and actual expected-versus-observed tests. A trace or unrelated screenshot does not prove execution, and this Python course alone does not certify the wider two-language KS3 objective.


Learning evidence

Submit a runnable modular Python file with at least two functions, a composed caller, documented parameters and return values with units, a call trace and separate component/integration tests. Include normal, zero, boundary and invalid cases with independently calculated expectations and actual observed outputs. Paper routes remain available but must be labelled as traces, not executions.


OER and Wikipedia

Original measurement, duration and report contracts, programs, traces, tests and exercises. Python Software Foundation tutorial on functions and modules support the language semantics; concrete code and learning examples are independently authored. DfE Computing programme of study, KS3 abstraction and modular programming. Year 8 sequencing is editorial; the broader two-language objective requires other courses as well. Primary references checked 14 November 2026 local time. Original videos identify Corey Schafer. Unchanged Commons illustrations retain their authors and licences; the photographed Python and temperature flowchart are explicitly not the original course implementation.

Python Code.jpg, Weal2019, CC0. Unchanged original; caption and learning activities are original.

Illustration for the area of a rectangle.svg, Stephan Kulla, CC0. Unchanged original; caption and learning activities are original.

Flowgorithm Input Process Output.svg, Dave Braunschweig, CC BY-SA 4.0. Unchanged original; caption and learning activities are original.


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...