Python Lesson 6: Functions

Python Lesson 6: Functions featured illustration

πŸ“Ž This article includes 2 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Beginner Course Β· Lesson 6 of 12

In this article
  1. def and return
  2. More useful functions
  3. Scope
  4. Modules: functions in another file
  5. Where beginners go wrong
  6. Practice
  7. Continue learning

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.

Advertisement

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)
  • amount and rate are parameters; rate=0.18 is a default used when you don’t pass one.
  • return sends the answer back. Without it, the function returns None.
  • 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']
πŸ’‘ A good function does one thing and has a name that says what: clean_mobile(), fy_label(), send_report(). If you can’t name it simply, it’s probably doing too much.

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.

Advertisement

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

⬇ Download all 2 files (ZIP Β· 608 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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong