Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is the difference between return and print?
What you need to know
Two different jobs
1def add_ret(a, b):2 return a + b34def add_pr(a, b):5 print(a + b)67x = add_ret(2, 3)8y = add_pr(2, 3) # prints: 59print(x, y) # 5 None10try:11 y + 112except TypeError as e:13 print(e) # unsupported operand type(s) for +: 'NoneType' and 'int'add_pr showed a 5 on screen, but the program received None. The error only appears later, in the line that tries to use the value — often far from the real cause.
return ends the function
Nothing after a return runs. That is useful for early exits, and a classic bug inside loops:
1def first_long(words):2 for w in words:3 if len(w) > 5:4 return w # exit as soon as we find one5 return None # explicit: nothing found67print(first_long(["upi", "refund", "failed"])) # refundReturning several values
return count, accuracy returns one tuple, which the caller unpacks: n, acc = evaluate(...).
print vs logging
print goes to standard output with no timestamp, no level and no way to switch it off. Production code uses the logging module, which adds levels (DEBUG, INFO, WARNING, ERROR), timestamps, and can send output to files or a log service.
A real-life example
An intern writes an evaluation function for two prompt versions:
1import logging2logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")34def evaluate(preds, labels):5 correct = sum(p == l for p, l in zip(preds, labels))6 return {"accuracy": correct / len(labels), "n": len(labels)}78labels = ["refund", "kyc", "refund", "other"]9v1 = evaluate(["refund", "other", "other", "other"], labels)10v2 = evaluate(["refund", "kyc", "refund", "kyc"], labels)11best = max([("v1", v1), ("v2", v2)], key=lambda pair: pair[1]["accuracy"])12logging.info("best prompt %s with %s", best[0], best[1])13# INFO best prompt v2 with {'accuracy': 0.75, 'n': 4}The first version of evaluate printed Accuracy: 0.5 and Accuracy: 0.75. It looked fine in a notebook, but when the team wanted to pick the better prompt automatically, there was nothing to compare — both calls returned None. Returning a dict made the comparison, a unit test and a dashboard all possible.
Follow-up questions to expect
- "Can a function return multiple values?" — It returns one tuple, which looks like multiple values when you unpack it:
a, b = f(). - "Why use logging instead of print?" — Levels, timestamps, configurable destinations, and the ability to silence debug output in production without editing code.
- "What does
returnwith no value do?" — It ends the function and returnsNone.