Python Essentials for AI Engineer

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

Python
def add_ret(a, b):    return a + bdef add_pr(a, b):    print(a + b)x = add_ret(2, 3)y = add_pr(2, 3)       # prints: 5print(x, y)            # 5 Nonetry:    y + 1except TypeError as e:    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:

Python
def first_long(words):    for w in words:        if len(w) > 5:            return w          # exit as soon as we find one    return None               # explicit: nothing foundprint(first_long(["upi", "refund", "failed"]))    # refund

Returning 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:

Python
import logginglogging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")def evaluate(preds, labels):    correct = sum(p == l for p, l in zip(preds, labels))    return {"accuracy": correct / len(labels), "n": len(labels)}labels = ["refund", "kyc", "refund", "other"]v1 = evaluate(["refund", "other", "other", "other"], labels)v2 = evaluate(["refund", "kyc", "refund", "kyc"], labels)best = max([("v1", v1), ("v2", v2)], key=lambda pair: pair[1]["accuracy"])logging.info("best prompt %s with %s", best[0], best[1])# 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 return with no value do?" — It ends the function and returns None.