A function gives a calculation a named input/output boundary.
Return a result when other code needs to use it; printing is a display action, not a substitute for a return value. Test simple cases before adding complexity.
Separate calculating from displaying
A function creates a named boundary around a calculation. Its parameters describe inputs, and return passes a result back to the caller. A function that reaches its end without returning a value returns None. Printing a number inside the function does not make that number available as the return value.
This distinction matters when composing calculations. If a total function returns 13, another expression can compare it with a target or use it in arithmetic. If the function only prints 13, the caller receives None and a later arithmetic operation can fail. Keeping display outside the calculation also makes testing easier.
Run the provided normal and empty-list cases. Add a one-record case with an independently known answer. Replace return with print and observe both the output produced inside the function and the value printed by the caller. Restore the return before using the function in a second calculation.
The bigger picture
A Python program transforms values according to explicit operations. To understand a program, trace the values and their types, not just the printed output. Text that looks like a number remains text until an operation converts it.
- Read inputs
- Trace operations
- Run code
- Test another case
Concepts to keep close
- Type
- The kind of value, which determines the operations that have meaning for it.
- Control flow
- The order in which statements execute, including branches and loops.
- Return value
- A result passed back to calling code; printing a result is a different action.
Reasoning through the problem
Define the input and returned result.
Separate display from calculation.
Test an ordinary and empty collection.
Use the idea carefully
Predict output before running a short example. Change one value or operation and explain the new result. Test an ordinary case, an empty input and a boundary. Read errors from the final exception message back to the relevant line. A passing example is evidence about that input, not proof that every possible input works.