smartyfy.mrindigi.com

Python Master Course V2 — 053. Return Values and Function Composition

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 06 · LESSON 053 / 200

Return Values and Function Composition

Estimated study: 60–90 minutes. Prerequisite: Lesson 52, plus Python variables, collections, conditions and loops.

Course hub

Video lesson

Video not yet available. This is a reserved video link/player location.

Learning objectives

Use return values to combine smaller calculations. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Use return values to combine smaller calculations. A function creates a reusable abstraction: it accepts inputs, performs a focused responsibility, and may return an output. Prefer small named functions with clear contracts. Validate external inputs at system boundaries, choose meaningful names, and separate calculation from printing so functions can be tested. Avoid hidden state where possible. Study the example, then change the inputs and explain the result.

Professional design checklist: define the purpose; choose inputs and outputs; consider invalid and edge-case values; write a minimal implementation; test normal, boundary and failure paths; then document the contract.

Understand and apply: Return Values and Function Composition

The result of a call is a value

A return statement ends the current function call and supplies a value to the caller. That value can be assigned to a variable, passed to another function, or compared in a test. Printing is different: it writes a representation to an output stream. A function that only prints has not supplied the printed object as its result. If execution reaches the end of the body, or reaches a bare return, the result is None.

Python code

def doubled(value):
    return value * 2

def show_doubled(value):
    print(value * 2)

print(doubled(4) + 1)
result = show_doubled(4)
print(result)

Expected output

9
8
None

The first call returns 8, so adding 1 produces 9. The second function displays 8 during its execution, then returns None implicitly. The assignment stores None, and the final print exposes that result. Trying show_doubled(4) + 1 would print 8 and then raise TypeError. Debug the missing return rather than converting the printed text back into data.

Trace composition one step at a time

Composition means feeding the result of one operation into another. To make the data flow visible, begin with named intermediate values. This example uses whole-number points rather than currency so its arithmetic does not hide financial rounding decisions. The contract accepts a list of nonnegative integer point values and an integer deduction between zero and the subtotal; the fixture below stays within that contract. These small functions assume valid inputs; they do not implement runtime validation.

Python code

def subtotal(points):
    return sum(points)

def subtract_deduction(amount, deduction):
    return amount - deduction

def add_bonus(amount):
    return amount + 5

base = subtotal([20, 30])
after_deduction = subtract_deduction(base, 10)
final_points = add_bonus(after_deduction)
print(base, after_deduction, final_points)
print(add_bonus(subtract_deduction(subtotal([20, 30]), 10)))

Expected output

50 40 45
45

In the nested expression, the inner subtotal must finish before subtraction can receive its amount. Subtraction must then finish before the bonus function runs. The compact expression and the expanded version describe the same dependency chain. Keep intermediate names when they clarify a business step or make a failing value easy to inspect. Do not compress every workflow into one line simply because nesting is possible.

Several values still form one returned object

Python code

def extremes(values):
    if not values:
        raise ValueError("values must not be empty")
    return min(values), max(values)

limits = extremes([7, 2, 9])
lowest, highest = limits
print(limits)
print(highest - lowest)

Expected output

(2, 9)
7

The comma constructs a tuple, so this function returns one tuple containing two values. Unpacking assigns its elements to two names in order. Returning structured data is useful when a caller needs both a result and supporting information. The empty-input guard matters because a minimum or maximum is undefined for an empty collection. Test every branch that returns or raises, not just the first successful call.

The introductory subtotal-and-tax example illustrates composition using binary floating-point arithmetic. Treat it as a toy model. Real invoice calculations need a declared Decimal and rounding policy, developed in lesson 060. Returning a value does not automatically make a function pure: it could also modify an input or print. For predictable composition, prefer calculations whose dependencies are explicit and whose observable behavior is clearly documented.

Progressive runnable Python example

Requires Python 3.10+. Save as lesson53.py, run with python lesson53.py or python3 lesson53.py.

def subtotal(price, qty):
    return price * qty
def with_tax(amount, rate):
    return amount * (1 + rate)
print(with_tax(subtotal(100, 2), 0.05))

Expected output:

210.0

This subtotal-and-tax example illustrates composition with binary floats. It is a teaching model; real invoice amounts need the Decimal validation and explicit rounding policy developed in Lesson 060.

Additional exploration

Run the example with different valid inputs. Predict the result before executing. Extract repeated operations into a named function and write at least one assertion for the expected output. For invalid inputs, decide whether to return a documented result or raise an informative exception.

Guided practical project

Compose subtotal, discount and tax functions. Start with a short requirements table identifying inputs, outputs and validation rules. Implement the smallest working function first, add a separate caller, and test at least three scenarios: typical input, boundary input and invalid input. Print a labeled report only at the program’s outermost layer.

Acceptance criteria: results are deterministic for the same inputs; no unexpected shared mutable state; invalid input is handled deliberately; output is documented; at least three assertions are included in your local project.

Common mistakes and debugging

  • Confusing print with return; printing does not pass a value back to the caller.
  • Using ambiguous names or overly long functions; divide responsibilities clearly.
  • Assuming all inputs are valid; validate values at appropriate boundaries.
  • Relying on global mutable variables; pass dependencies explicitly.
  • Skipping edge-case tests; test zero, empty, negative or missing values as applicable.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

Optional hint for question 1

Printing a result and returning a result have different effects on the caller.

1. Why does assigning the result of show_doubled(4) produce None?

Answer and reasoning: Its body calls print but has no return value. The printed 8 is a side effect; the call result stored by the assignment is None.

2. Expand add_bonus(subtract_deduction(subtotal([3, 7]), 2)) into values.

Answer and reasoning: The subtotal is 10, subtraction produces 8, and add_bonus produces 13. The outer function cannot use its argument until the inner call has produced it.

3. What does return low, high actually return?

Answer and reasoning: It returns one tuple containing low and high. A caller may retain that tuple or unpack it into two variables. An incorrect number of unpacking targets raises ValueError.

4. What happens to statements after an executed return in the same function call?

Answer and reasoning: Ordinary subsequent statements in that function body are skipped because return ends the call. A conditional return only ends calls that reach it; other branches still need deliberate return behavior.

5. How would you test extremes at its smallest valid input and at an invalid input?

Answer and reasoning: For one value, use assert extremes([4]) == (4, 4). The single value is both minimum and maximum. For an empty list, expect ValueError; returning a made-up zero pair would conceal that no extrema exist.

Mastery checkpoint

Before moving on, explain the lesson concept, run the example, complete the project, write three tests, and explain why your function design is maintainable. The five-question self-check above provides answer explanations; it does not store account-level completion.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.