Published lesson · 30 minutes

Write functions

Objective: Define a function with parameters, return a value and test it with more than one input.

Understand the idea

Write functions works best when the learner can explain the reason behind each step, not just copy a result. A function packages a named calculation; parameters make the inputs visible and a return value lets another step use its result.

A learner calculates a weekly saving target from a goal amount and number of weeks, then prints the result in a practice budget. Treat the names and details as invented practice information; the example is for learning a method and does not describe a live service.

A dependable sequence is: Write the simplest function first, validate a zero or negative number of weeks, return the result and call it from a separate print step. Write down the important decision before you begin so another person can follow the reasoning.

Use `return` for the computed value instead of printing inside every branch. Keep example amounts fictional and explain the units. Compare the result with the objective, then change one thing at a time if the first attempt does not work.

Change the goal amount and predict the returned weekly target. Explain one assumption that would need checking before anyone used a similar result outside the classroom.

Keep a short record of the choices you made and the evidence you used to check them. A useful practice result is understandable by another learner, stays within the stated scope and makes its limitations visible before anyone relies on it.

Worked examples

Write functions: practice example

Explore how write functions supports the lesson objective with a small synthetic example.

main.py

def weekly_target(goal, weeks):
    if weeks <= 0:
        return None
    return (goal + weeks - 1) // weeks

print(weekly_target(120, 6))

Practice tasks

  1. Explore write functions

    Use the worked example for “Write functions”. Change one small detail to suit a different synthetic community situation, then explain what you expected and how you checked whether the change still met the lesson objective.

  2. Build a Python practice example

    Create a small practice result that demonstrates this objective: Define a function with parameters, return a value and test it with more than one input. Use only synthetic information, keep the first version focused, and write down one limitation that a later version should address.

  3. Review and explain the result

    Review your “Write functions” result as if another learner will use it without your explanation. Identify one strength, one exact point that may be unclear, and a revision that would make the result easier to understand or use.

Write functions becomes easier when you write the simplest function first, check the result and explain the choice to another learner.

Course overview