
📎 This article includes 2 downloadable practice files ↓
In this article
When you copy the same calculation into three places, a change means fixing it three times. A function names a piece of logic once; you call it wherever you need it. Excel 365’s LAMBDA is the same idea.
def and return
def gst(amount, rate=0.18):
"""Return GST on an amount (default 18%), rounded to paise."""
return round(amount * rate, 2)
gst(1000) # 180.0
gst(1000, 0.12) # 120.0
gst(amount=2500, rate=0.05)
amountandrateare parameters;rate=0.18is a default used when you don’t pass one.returnsends the answer back. Without it, the function returnsNone.- The triple-quoted line is a docstring: hover over the function in VS Code to see it.
More useful functions
def fy_label(year, month):
start = year - (month < 4) # True counts as 1
return f"FY {start}-{str(start + 1)[2:]}"
def grade(marks):
if marks >= 90: return "A+"
if marks >= 75: return "A"
if marks >= 60: return "B"
if marks >= 40: return "C"
return "F"
[grade(m) for m in (95, 80, 61, 40, 12)] # ['A+', 'A', 'B', 'C', 'F']
Scope
Variables created inside a function exist only inside it. Pass values in as parameters and get results out with return, rather than relying on outside variables.
Modules: functions in another file
Save your helpers in helpers.py, then in another script: from helpers import gst, fy_label. That’s how you build a personal toolkit.
Where beginners go wrong
| Mistake | Effect |
|---|---|
| print instead of return | Shows a value but the caller gets None |
| Calling before defining | NameError; define functions at the top |
| Forgetting the brackets: total = gst | Stores the function itself, not a result |
Practice
Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.
📎 Practice files for this article
- 🐍Lesson 6 scriptThe complete script from this lesson, tested.⬇ PY · 563 B
- 📄Expected outputWhat the script prints when you run it.⬇ TXT · 64 B
Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.