Writing Your Own Functions · practice
Return Is Not Print
Printing and returning can both make a
print(value)displays text in the output.return valuesends a value back to the caller.
Confusing them produces one of the most common
A printed value is not handed back
Run this example:
The first line of output comes from inside the function. The second ends with None.
Every Python function returns a value. If execution reaches the end without an explicit None. Printing something along the way does not change that.
This version hands the
Now result contains the string. The caller chooses to display it.
Ask what the caller needs
Use print when the function’s job is specifically to display something:
def show_count(items):
print(f"Items stored: {len(items)}")
Use return when the caller needs the value for another operation:
def count_message(items):
return f"Items stored: {len(items)}"
The returned message can be printed, stored, combined with other text, or checked in a test.
Neither version is universally correct. The function’s responsibility decides. Trouble starts when the caller expects a value from a function that only prints.
A useful debugging question
If you see None where you expected a result, inspect the function:
Does it reach an explicit
return?Is it only printing the value?
Did you accidentally put
returninside a branch that did not run?
That short checklist will solve many beginner function bugs.
You want to build a price, store it in total, and compare it with a budget. What should calculate_total do?
Task
The current build_summary prints its message, so summary receives None and the program prints an unwanted second line.
Change the print call.
Expected output:
Lisbon for 4 days
The function must also work with other