Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 05 / Stage 1

Functions

Goal: Write your own reusable functions with clear inputs, outputs and names. Time: ~1 hour

What you will learn

  • def and return (and why return is not print)
  • Returning many values, and the None default
  • Parameters: positional, keyword, default, keyword-only, *args, **kwargs
  • Unpacking a list or dict into a function call
  • The mutable default argument trap
  • Scope: local, global, LEGB, and the global keyword
  • Docstrings and simple type hints
  • lambda with sorted(key=...)
  • Recursion: base case, factorial, sum of digits, folder size
  • Functions as values (passing a function into another function)

Topics in this part

Practice

Python workbench โ€” write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Write each answer as a function. Call it at the bottom with the sample values so the file runs on its own.


Exercise 1: Greeting card

Scenario: A sweet shop prints a greeting on every box. What to do: Write greet(name, festival="Diwali") that returns (not prints) a greeting. Print greet("Asha") and greet("Ravi", "Holi").

Sample output:

Happy Diwali, Asha!
Happy Holi, Ravi!

๐Ÿ’ก Hint: Use an f-string and a default value in the def line.


Show the solution to Exercise 1
"""Exercise 1: Greeting card (default argument + return).

Run: python ex01.py   (macOS/Linux: python3 ex01.py)
"""


def greet(name: str, festival: str = "Diwali") -> str:
    return f"Happy {festival}, {name}!"


print(greet("Asha"))
print(greet("Ravi", "Holi"))

Exercise 2: Marks report

Scenario: A teacher wants the lowest, highest and average marks of a class. What to do: Write marks_report(marks) that returns three values: lowest, highest, average (rounded to 1 decimal). Call it with [72, 95, 64, 88], unpack the three values and print them.

Sample output:

lowest=64 highest=95 average=79.8

๐Ÿ’ก Hint: return min(marks), max(marks), round(sum(marks) / len(marks), 1).


Show the solution to Exercise 2
"""Exercise 2: Marks report (returning several values).

Run: python ex02.py   (macOS/Linux: python3 ex02.py)
"""


def marks_report(marks: list[int]) -> tuple[int, int, float]:
    return min(marks), max(marks), round(sum(marks) / len(marks), 1)


lowest, highest, average = marks_report([72, 95, 64, 88])
print(f"lowest={lowest} highest={highest} average={average}")

Exercise 3: Split the bill

Scenario: Friends at a cafe add up any number of item prices. What to do: Write split_bill(*prices, people=2) that adds all prices and returns each person's share (rounded to 2 decimals). people must be keyword-only. Print split_bill(250, 180, 90) and split_bill(250, 180, 90, people=4).

Sample output:

260.0
130.0

๐Ÿ’ก Hint: *prices is a tuple, so sum(prices) works.


Show the solution to Exercise 3
"""Exercise 3: Split the bill (*args + keyword-only argument).

Run: python ex03.py   (macOS/Linux: python3 ex03.py)
"""


def split_bill(*prices: float, people: int = 2) -> float:
    return round(sum(prices) / people, 2)


print(split_bill(250, 180, 90))
print(split_bill(250, 180, 90, people=4))

Exercise 4: Student profile

Scenario: A college form has two required fields and many optional ones. What to do: Write build_profile(name, roll_no, **details) that returns a dict with all fields. Print build_profile("Meera", 21, city="Chennai", branch="CSE"). Then print a second profile made by unpacking form_data with **.

Starting data:

form_data = {"name": "Arjun", "roll_no": 7, "city": "Jaipur", "hostel": True}

Sample output:

{'name': 'Meera', 'roll_no': 21, 'city': 'Chennai', 'branch': 'CSE'}
{'name': 'Arjun', 'roll_no': 7, 'city': 'Jaipur', 'hostel': True}

๐Ÿ’ก Hint: Start with profile = {"name": name, "roll_no": roll_no} then profile.update(details).


Show the solution to Exercise 4
"""Exercise 4: Student profile (**kwargs + unpacking a dict).

Run: python ex04.py   (macOS/Linux: python3 ex04.py)
"""


def build_profile(name: str, roll_no: int, **details) -> dict:
    profile = {"name": name, "roll_no": roll_no}
    profile.update(details)          # add all the optional fields
    return profile


print(build_profile("Meera", 21, city="Chennai", branch="CSE"))

form_data = {"name": "Arjun", "roll_no": 7, "city": "Jaipur", "hostel": True}
print(build_profile(**form_data))    # unpack the dict into the call

Exercise 5: Fix the attendance bug

Scenario: This function should start a new attendance list for each class, but names keep piling up.

Starting data:

def mark_present(name, present=[]):
    present.append(name)
    return present

What to do: Fix it so each call without a list starts fresh, but passing a list still adds to it. Print mark_present("Asha"), mark_present("Ravi") and mark_present("Kiran", ["Asha"]).

Sample output:

['Asha']
['Ravi']
['Asha', 'Kiran']

๐Ÿ’ก Hint: Use None as the default.


Show the solution to Exercise 5
"""Exercise 5: Fix the attendance bug (mutable default).

Run: python ex05.py   (macOS/Linux: python3 ex05.py)
"""


def mark_present(name: str, present: list[str] | None = None) -> list[str]:
    if present is None:
        present = []                 # new list on every call
    present.append(name)
    return present


print(mark_present("Asha"))
print(mark_present("Ravi"))
print(mark_present("Kiran", ["Asha"]))

Exercise 6: Leaderboard

Scenario: A quiz app shows players sorted by score, high to low. Ties are sorted by name Aโ†’Z. What to do: Write leaderboard(players) where players is a list of (name, score) tuples. Use sorted with a lambda, then print the rank, name (padded to 5 characters) and score.

Starting data:

players = [("Ravi", 80), ("Asha", 95), ("Neha", 80), ("Kiran", 60)]

Sample output:

1. Asha  95
2. Neha  80
3. Ravi  80
4. Kiran 60

๐Ÿ’ก Hint: key=lambda p: (-p[1], p[0]) makes a tuple for each player. Tuples compare item by item (Part 4), so this sorts by score high to low (-p[1]), then by name. Use enumerate(ranked, start=1) for the rank and {name:<5} to pad the name.


Show the solution to Exercise 6
"""Exercise 6: Leaderboard (sorted with a lambda key).

Run: python ex06.py   (macOS/Linux: python3 ex06.py)
"""


def leaderboard(players: list[tuple[str, int]]) -> None:
    # -score puts high scores first; name breaks ties A -> Z
    ranked = sorted(players, key=lambda p: (-p[1], p[0]))
    for rank, (name, score) in enumerate(ranked, start=1):
        print(f"{rank}. {name:<5} {score}")


players = [("Ravi", 80), ("Asha", 95), ("Neha", 80), ("Kiran", 60)]
leaderboard(players)

Exercise 7: Price rules

Scenario: A shop has different pricing rules: student discount, festive offer, and "add GST". What to do:

  1. Write three small functions: student(price) (10% off), festive(price) (โ‚น200 off, never below 0), add_gst(price) (+18%).
  2. Write apply_rules(price, *rules) that applies each rule function in order and returns the final price rounded to 2 decimals.
  3. Print apply_rules(1000, student, add_gst), apply_rules(1000, festive, student, add_gst) and apply_rules(150, festive).

Sample output:

1062.0
849.6
0

๐Ÿ’ก Hint: Loop: for rule in rules: price = rule(price). max(price - 200, 0) never goes below 0.


Show the solution to Exercise 7
"""Exercise 7: Price rules (passing functions as values).

Run: python ex07.py   (macOS/Linux: python3 ex07.py)
"""


def student(price: float) -> float:
    return price * 0.9


def festive(price: float) -> float:
    return max(price - 200, 0)


def add_gst(price: float) -> float:
    return price * 1.18


def apply_rules(price: float, *rules) -> float:
    for rule in rules:               # each rule is a function
        price = rule(price)
    return round(price, 2)


print(apply_rules(1000, student, add_gst))
print(apply_rules(1000, festive, student, add_gst))
print(apply_rules(150, festive))

Exercise 8: Count files and digits (recursion)

Scenario: A backup tool must count all files in nested folders, and a form checks how many digits a PIN code has. What to do:

  1. The folder is a nested dict: a value that is a dict is a sub-folder, anything else is a file. isinstance(value, dict) is True when value is a dict. Write a recursive count_files(folder) and print count_files(drive).
  2. Write a recursive count_digits(n) that returns how many digits a whole number n (0 or more) has, without using str() or len(). Print count_digits(560001) and count_digits(7).

Starting data:

drive = {"a.txt": 1, "Photos": {"b.jpg": 2, "Old": {"c.jpg": 3}}, "d.pdf": 4}

Sample output:

4
6
1

๐Ÿ’ก Hint: count_files: for each value, if it is a dict add count_files(value), else add 1. An empty folder has 0 files. count_digits: the base case is a number below 10 (one digit). Otherwise it is 1 + the digits of n // 10 (the number without its last digit).

Show the solution to Exercise 8
"""Exercise 8: Count files in a folder tree, and count digits (recursion).

Run: python ex08.py   (macOS/Linux: python3 ex08.py)
"""


def count_files(folder: dict) -> int:
    count = 0                        # an empty folder gives 0 (base case)
    for value in folder.values():
        if isinstance(value, dict):
            count += count_files(value)   # ask the sub-folder
        else:
            count += 1
    return count


def count_digits(n: int) -> int:
    if n < 10:                       # base case: a single digit
        return 1
    return 1 + count_digits(n // 10)  # n // 10 drops the last digit


drive = {"a.txt": 1, "Photos": {"b.jpg": 2, "Old": {"c.jpg": 3}}, "d.pdf": 4}
print(count_files(drive))
print(count_digits(560001))
print(count_digits(7))

Common mistakes

Mistake Why it is wrong Fix
Using print instead of return The caller gets None and cannot use the value return the value; print outside
def f(items=[]) The same list is shared between calls def f(items=None) then if items is None: items = []
Forgetting the base case in recursion It never stops โ†’ RecursionError Always write the stop condition first
apply_rule(prices, festive_offer()) Calls the function instead of passing it Pass the name only: festive_offer
Using global to share data Hidden changes, hard to test Pass values in, return new values
Default before non-default: def f(a=1, b) SyntaxError Put defaults at the end: def f(b, a=1)
Long logic in a lambda Hard to read Use a normal def with a good name

Quick recap

  • def makes a function; return sends a value back; no return means None.
  • return a, b returns a tuple; unpack with x, y = f().
  • Defaults make arguments optional; after * arguments must be named.
  • *args โ†’ tuple of extras, **kwargs โ†’ dict of extras; * and ** also unpack in calls.
  • Never use a mutable default like []; use None.
  • Python looks up names in LEGB order; avoid global.
  • lambda is for tiny functions, mostly key= in sorted.
  • Recursion needs a base case; functions can be passed around like values.

Checklist

  • I can explain the difference between return and print.
  • I can return two values and unpack them.
  • I can use default, keyword and keyword-only arguments.
  • I can write a function with *args and **kwargs.
  • I know why items=[] is a bug and how to fix it.
  • I can explain LEGB and why global is best avoided.
  • I can sort a list of tuples with sorted(key=lambda ...).
  • I can write a recursive function with a base case.

Search the guide