Writing Your Own Functions · practice
Return Is Not Print
Here is a
The greeting appears, so the function seems to work. The second line shows the problem: result holds None, not the greeting.
The output is for people, not for your program
print and
print(value)sends text to the output, where a person can read it.return valuesends a value back to the code that called the function.
Once text is printed, your program cannot read it back. The greeting is on the screen, but nothing in the program holds it.
build_message has no return, and every Python function returns a value. When a function finishes without reaching a return, it returns the special value None. None is Python’s value for “nothing here,” and that is what result received.
Change print to return, and the caller gets the
Now there is one line of output, and the caller printed it. The function built the greeting and the caller decided what to do with it.
A stray None in the output
The same mistake can also show up as an extra line. This caller prints the call directly:
Follow the order Python runs it in. Inside the call, build_message prints the greeting. The call then ends and returns None, and the outer print displays that None.
You have now seen None turn up inside a message and on a line of its own. In both cases, check the function that was called: does it reach a return with the value you want, or does it only print that value?
Ask what the caller needs
Some functions exist to display something. Printing is their job:
def show_count(items):
print(f"Items stored: {len(items)}")
Other functions produce a value that the caller will use:
def count_message(items):
return f"Items stored: {len(items)}"
The caller can print the returned message, but it can also store it, add it to a show_count can only display its message.
Neither kind of function is wrong. The mistake is calling a function that only prints and expecting to get a value back. When you write a function, ask whether the caller needs to see the result or use it. If you are not sure, return the value. The caller can always print it.
A program needs calculate_total to work out a price. The caller will store the result in total and compare it with a budget. What should the function do with the price it calculated?
Task
The starter’s build_summary prints its message instead of returning it. Run the starter first: the summary appears, followed by a stray None line.
Change the summary and the final print call, so the summary is printed once, by the caller.
Expected output:
Lisbon for 4 days
The function must also work with other
After it passes, use Step in the exercise editor. Watch build_summary reach summary receive the string in the Locals panel.