Returning a Value Versus Printing It

A return passes a value to the caller. A print call writes a representation to an output stream.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace the caller's variables
  2. Combine the two at the edge
  3. Separate a calculation from its presentation
  4. Leave formatting choices close to the reader

Trace the caller's variables

If a Python function prints three and has no explicit return, assigning its result gives None. A function returning three can supply a value for a later multiplication without writing to the screen. Trace the return to the caller to locate the value.

Combine the two at the edge

A report calculation can return a number. A command can decide when and how to print that number, including the unit and display precision. Representations displayed as text describe formatting choices separate from the calculation.[1][2]

Separate a calculation from its presentation

Suppose subtotal(3, 7) produces twenty-one. Code that wants to add a five-unit delivery charge needs the number as a return value. A function that only prints twenty-one to standard output can look right during a manual run but supplies None to its Python caller if it reaches the end without an explicit return. Verify the result directly, then test the user-facing code that prints the total twenty-six. See function contracts for the difference between return values and observable effects.

Leave formatting choices close to the reader

A numeric result can be formatted as currency in a command-line tool and serialized as data in a web handler. Printing from the pricing calculation hard-codes formatting and can add unwanted output for users calling it in a loop. Keep intentional diagnostics distinct from program output. A function whose purpose is exclusively display can still return useful status information if the caller needs it. Test one call in isolation and another with standard output captured. See formatting and parsing.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩