Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

2.2 Return Values

How it works

A function without an explicit return yields the null object. Returning is different from printing, and only one of them is usable by the caller.

Return results and let the caller decide whether to display them.

Common error

Printing inside a function then trying to use the result, which silently gives nothing.

Worked example

Python

def double(value):
    return 2 * value

result = double(6)
print(result + 1)

Output

13

return sends a value to the caller and ends the function. Printing inside a function is a different action and does not by itself return that printed value.

Exercises

2.2.1 · Trace

Determine the exact output and explain the state changes.

Python

def show(value):
    print(value)

result = show(4)
print(result)
Show solution

Output

4
None

The function prints 4 and implicitly returns None because it has no explicit return value.

2.2.2 · Write code

Write absolute(value) without using abs and test -3 and 2.

Show solution

Return from the negative and nonnegative cases.

One valid solution

def absolute(value):
    if value < 0:
        return -value
    return value

print(absolute(-3), absolute(2))

Expected output

3 2
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic