Skip to course content
Free course

Python Foundations / Module 5 / Return Values: Separate Work from Display

Module 5 lesson

Return Values: Separate Work from Display

Unit ID: M05-U02 Estimated active time: 22-30 minutes

print and return are different

This function prints but does not return the calculated value:

def show_total(a, b):
    print(a + b)
result = show_total(3, 4)
print(result)

The function displays 7, but result is None.

Use return when the caller needs the value:

def calculate_total(a, b):
    return a + b

result = calculate_total(3, 4)
print(result)

Now result is 7.

Return ends the function call

def classify_hours(hours):
    if hours < 0:
        return "invalid"
    return "accepted"

When the first return runs, later lines in that call are skipped.

Return several related values carefully

def hour_summary(hours):
    return len(hours), sum(hours)

count, total = hour_summary([8, 12, 4])

Python returns a tuple, which is unpacked. Use a dictionary when several returned values need labels and may grow over time.

Separate calculation and presentation

def average_hours(total_hours, module_count):
    return total_hours / module_count

average = average_hours(32, 10)
print(f"Average hours: {average:.1f}")

The function calculates. The caller decides how to display. This makes the result reusable in a report, test, or later calculation.

Practice

Refactor a function that prints a cleaned status so it returns the clean string. Call it, compare the returned value with "planned", and print a labelled message outside the function.

Takeaway

return gives a value back to the caller. print() displays information. Keeping calculation separate from display makes functions easier to reuse and verify. Next, we will examine local scope and side effects.