Lesson 14 of 16 · 52 min · UG / professional
Functions: return, None and a one-line spec
def names a contract. return hands a value back. Forget return and callers get nothing useful (None on a laptop). A first-line string is a docstring — the spec the next intern reads.
Lab recipe cards
Functions are reusable procedures.
You will be able to
- ✓ Define def, pass arguments, return values
- ✓ Know a missing return is None on a laptop
- ✓ Put a one-line docstring as the spec
A contract with a name
def late_fee(days): names a contract. Parameters are the names in the def line; arguments are what you pass. return hands a value back and ends the call. Forget return and the laptop gives None — callers then print inside the function to ‘see’ the answer, and tests die.
The first string in the body is a docstring. Tools and help() read it. Write the wall-notice example there: late_fee(0) is 0. Polymorphic idea: the same function can take ints or (later) decimals if the operations exist — do not type-declare everything; do document what you meant.
Call by object reference
Passing a list does not copy it. If the function appends, the caller sees it. Pass a snapshot if the function should not edit the source. Functions are objects — you can assign f = late_fee and call f(4).
Words that matter
- def
- Define a named function.
- return
- Send a value back and end this call.
- docstring
- First string in the body — the spec.
- None
- The laptop value when you did not return.
Common mistakes
Avoid: Printing the fee inside the function and returning nothing.
Do this: return the fee; print at the edge.
Run it step by step
Each box is a real program. Press Run, change a number, Run again — the output must follow your code.
1. Step 1 — one input, one output
net_pay(100) is 88 after PF 12.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
2. Step 2 — compose two contracts
GST after PF.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Example program — A rule two callers share
Change 12 in one place.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Hours to pay
pay(hours) returns hours * 120. Print pay(3) so 360 appears.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.