Return a Value Instead of Printing It
Scenario
Compare two versions of canBook(freeSeats).
Try it yourself
Select each version to see which one an automated assertion can verify.
| Case | Result |
|---|---|
| function canBook(freeSeats) { print(freeSeats > 0) } | Select a choice above to see what happens. |
| function canBook(freeSeats) { return freeSeats > 0 } | Select a choice above to see what happens. |
| Caller formats returned boolean into "Accepted" / "Declined" at the UI edge | Select a choice above to see what happens. |
Reveal the explanation
- function canBook(freeSeats) { print(freeSeats > 0) }
Hard to test. The function prints to the console and returns nothing (None/undefined).
- function canBook(freeSeats) { return freeSeats > 0 }
Testable and reusable. assert(canBook(1) === true) checks the exact returned boolean.
- Caller formats returned boolean into "Accepted" / "Declined" at the UI edge
Clean separation: one rule function works for CLI, web UI, and tests alike.
Keep decision functions focused on returning values. Let the outer UI layer decide how to format or print that returned result.
Your turn
Refactor "def did_pass(score): print(score >= 60)" so a test can assert did_pass(60) is True.
Common mistake Leaving print() inside did_pass and forgetting return.
Check your work
def did_pass(score): return score >= 60.
Quick check
This browser could not save your progress. Changes last until you leave the page.