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







