liveBook · Manning

Return value

As explained in The Quick Python Book, Fourth Edition

A return value is the result supplied by a function to its caller when the function completes execution.

A return value is the result a function supplies to its caller. In Python, every function returns a value: an explicit return sends the specified result immediately, while reaching the end without one returns None. section 9.1

Handle a function's return value in several ways:

  • Assign it to a variable and use that variable like any other value. section 9.1
  • Leave it unassigned; the value is discarded, unless the call is the last statement in a cell, where it is displayed. section 9.1
  • Return before the function body ends; statements after the executed return do not run. section 9.1
  • Use a distinct variable name when capturing the result, so it does not replace the function name and make later calls fail. section 9.9.2

Capturing a factorial result

def fact(n): r = 1 while n > 0: r = r * n n = n - 1 return r fact(4) # displays 24 in a cell x = fact(4) # stores 24 in x section 9.1

Avoiding a function-name collision

for line in input_file: cleaned_line = clean_line(line) write_words_to_file(cleaned_line, output_file) Using cleaned_line preserves clean_line as a callable function. Assigning the result to clean_line instead makes the next loop iteration attempt to call a string. section 9.9.2

fact(4)                                             #1
 
24                                                  #2
 
x = fact(4)                                         #3
x
 
24
#1 No variable assigned to the return value.
#2 The value is printed, not saved.
#3 The variable x is assigned to the return value.

Compare an unassigned function call with a call whose return value is assigned to a variable. section 9.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains explicit and implicit returns, early termination, discarded results, assignment, and name-collision failure, without covering implementation internals.
Examples
Demonstrates factorial computation, displayed versus assigned results, and text-cleaning functions used in a word-processing pipeline.
What you can do after
Apply it via Python functions to capture results, discard them deliberately, return early, and avoid callable-name collisions.
How it connects
Connects return values with functions, procedures, variables, function calls, global variables, and code refactoring.

Also explained in

Compare how 8 books explain return value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.