{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"returning-values","title":"Returning: one value, several values, or nothing at all","url":"https://addaly.com/learn/python-for-ai/returning-values","position":24,"of":89,"minutes":7,"answer":"Return values instead of printing them, because a function that prints can only ever feed a terminal, while a function that returns feeds a file, a test, a request and a terminal.","keyIdea":"Return values instead of printing them, because a function that prints can only ever feed a terminal, while a function that returns feeds a file, a test, a request and a terminal."},"body":{"format":"markdown","text":"## `return` ends the function immediately\n\n```python\ndef first_even(numbers):\n    for n in numbers:\n        if n % 2 == 0:\n            return n\n    return None\n```\n\nThe `return` inside the loop stops the loop **and** the function. Nothing after it runs. That is why the guard-clause style from the branching lesson works so well: each early `return` removes a case and the remaining code gets simpler rather than more nested.\n\nA function with no `return` statement, or with a bare `return`, hands back `None`. This is not an error; it is a value, and it will show up later as `TypeError: 'NoneType' object is not subscriptable` if you forget.\n\n## Returning several values\n\n```python\ndef stats(numbers):\n    return min(numbers), max(numbers), sum(numbers) / len(numbers)\n\nlow, high, mean = stats([3, 9, 4])\n```\n\nPython has no special syntax here. The function returns one tuple, and the caller unpacks it. If you take only part of it, use `_` for the parts you ignore:\n\n```python\n_, high, _ = stats(readings)\n```\n\nUnpacking fails loudly if the count changes (`ValueError: too many values to unpack`) which is a feature. A function whose return shape changed will break at the call site rather than silently handing back something wrong.\n\n## When a tuple stops being a good idea\n\nAt three values, a tuple is fine. At five, callers start writing `result[3]` and nobody knows what position three is. Two better options:\n\n```python\nfrom typing import NamedTuple\n\nclass Stats(NamedTuple):\n    low: float\n    high: float\n    mean: float\n    count: int\n```\n\n`Stats(1, 9, 4.5, 3)` still unpacks like a tuple, still indexes like a tuple, and also supports `result.mean`. It costs four lines and removes a permanent source of confusion.\n\nOr return a dictionary, which is right when the set of keys is variable (a parsed API response, for instance) and wrong when it is fixed, because typos in keys are not caught anywhere.\n\n## Return, do not print\n\nThe distinction from the earlier functions lesson deserves one more pass, because it decides whether your code can be reused.\n\n```python\ndef report(rows):\n    for r in rows:\n        print(f\"{r['name']}: {r['total']}\")\n```\n\nThat function can do exactly one thing: write to a terminal. It cannot be tested without capturing standard output, cannot write to a file, cannot be sent over HTTP, and cannot be translated.\n\n```python\ndef format_report(rows):\n    return \"\\n\".join(\n        f\"{r['name']}: {r['total']}\" for r in rows\n    )\n\nrows = [\n    {\"name\": \"Asha\", \"total\": 42},\n    {\"name\": \"Ravi\", \"total\": 17},\n]\nprint(format_report(rows))\n```\n\nNow the same function serves a terminal, a file, an email and a test, and the test is one line: `assert format_report([...]) == \"...\"`. Push printing to the outermost layer of the program and keep everything underneath returning values.\n\n## Returning a value the caller must check\n\nThree ways to signal \"there was no answer\", each with a cost:\n\n- **Return `None`.** Cheap, and easy to forget to check. Fine when absence is ordinary and the caller obviously handles it.\n- **Return a default.** `get_price(item, default=0)` keeps the caller simple and can hide a real failure inside an average.\n- **Raise an exception.** Impossible to ignore, and correct when continuing would mean producing a wrong answer. The errors module covers this properly.\n\nWhichever you choose, choose it once per function and write it in the docstring. Functions that sometimes return `None` and sometimes raise are the ones that produce three-in-the-morning bugs.\n\nNever signal failure with a sentinel like `-1` or `\"ERROR\"`. It has the same type as a real answer, so it flows through arithmetic and string joins undetected until the total is wrong.\n\n## Returning early against a single exit\n\nSome traditions insist on one `return` per function. Python's does not, and guard clauses are the house style. The practical test is whether a reader can see all the ways out. Four early returns in a fifteen-line function are clear. Nine returns scattered through eighty lines are not, and that function wanted splitting anyway.\n\n## A function that returns nothing should say so\n\nIf a function's job is a side effect (writing a file, sending a request) return `None` and name it with a verb: `save_report`, `send_email`, `delete_row`. Functions that compute get noun-ish names: `total`, `format_report`, `parse_date`. The convention is not decoration; it means a reader can tell from the call site whether the result matters."},"check":{"question":"A price lookup returns `-1` when an item is unknown. Totals across the catalogue have been slightly low for months. What is the defect this illustrates?","options":[{"text":"The sentinel should have been 0, which is neutral in a sum and therefore safe.","correct":false,"tempting":"Swaps one in-band sentinel for another; zero is silently wrong in a division or an average and still cannot be distinguished from a real price."},{"text":"The failure signal has the same type as a real answer, so it flows through arithmetic undetected instead of stopping the calculation.","correct":true},{"text":"The function should print a warning when the item is unknown, so the operator can see the problem in the log.","correct":false,"tempting":"Adds visibility without fixing the arithmetic, and pushes output into a function whose job is to compute."},{"text":"Returning early from a lookup is the real problem; a single exit point would have made the bug obvious.","correct":false,"tempting":"Attributes the fault to control flow style rather than to the choice of an in-band failure value."}]},"prev":{"slug":"scope-and-globals","title":"Where a name lives, and why the function cannot see it","url":"https://addaly.com/learn/python-for-ai/scope-and-globals"},"next":{"slug":"docstrings-and-type-hints","title":"Saying what a function expects, and what checks it","url":"https://addaly.com/learn/python-for-ai/docstrings-and-type-hints"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Returning: one value, several values, or nothing at all', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/returning-values (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Returning: one value, several values, or nothing at all","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Return values instead of printing them, because a function that prints can only ever feed a terminal, while a function that returns feeds a file, a test, a request and a terminal.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"return-ends-the-function-immediately","runs":[{"text":"return","code":true},{"text":" ends the function immediately"}]},{"t":"code","lang":"python","label":"Python","text":"def first_even(numbers):\n    for n in numbers:\n        if n % 2 == 0:\n            return n\n    return None"},{"t":"p","runs":[{"text":"The "},{"text":"return","code":true},{"text":" inside the loop stops the loop "},{"text":"and","b":true},{"text":" the function. Nothing after it runs. That is why the guard-clause style from the branching lesson works so well: each early "},{"text":"return","code":true},{"text":" removes a case and the remaining code gets simpler rather than more nested."}]},{"t":"p","runs":[{"text":"A function with no "},{"text":"return","code":true},{"text":" statement, or with a bare "},{"text":"return","code":true},{"text":", hands back "},{"text":"None","code":true},{"text":". This is not an error; it is a value, and it will show up later as "},{"text":"TypeError: 'NoneType' object is not subscriptable","code":true},{"text":" if you forget."}]},{"t":"h2","id":"returning-several-values","runs":[{"text":"Returning several values"}]},{"t":"code","lang":"python","label":"Python","text":"def stats(numbers):\n    return min(numbers), max(numbers), sum(numbers) / len(numbers)\n\nlow, high, mean = stats([3, 9, 4])"},{"t":"p","runs":[{"text":"Python has no special syntax here. The function returns one tuple, and the caller unpacks it. If you take only part of it, use "},{"text":"_","code":true},{"text":" for the parts you ignore:"}]},{"t":"code","lang":"python","label":"Python","text":"_, high, _ = stats(readings)"},{"t":"p","runs":[{"text":"Unpacking fails loudly if the count changes ("},{"text":"ValueError: too many values to unpack","code":true},{"text":") which is a feature. A function whose return shape changed will break at the call site rather than silently handing back something wrong."}]},{"t":"h2","id":"when-a-tuple-stops-being-a-good-idea","runs":[{"text":"When a tuple stops being a good idea"}]},{"t":"p","runs":[{"text":"At three values, a tuple is fine. At five, callers start writing "},{"text":"result[3]","code":true},{"text":" and nobody knows what position three is. Two better options:"}]},{"t":"code","lang":"python","label":"Python","text":"from typing import NamedTuple\n\nclass Stats(NamedTuple):\n    low: float\n    high: float\n    mean: float\n    count: int"},{"t":"p","runs":[{"text":"Stats(1, 9, 4.5, 3)","code":true},{"text":" still unpacks like a tuple, still indexes like a tuple, and also supports "},{"text":"result.mean","code":true},{"text":". It costs four lines and removes a permanent source of confusion."}]},{"t":"p","runs":[{"text":"Or return a dictionary, which is right when the set of keys is variable (a parsed API response, for instance) and wrong when it is fixed, because typos in keys are not caught anywhere."}]},{"t":"h2","id":"return-do-not-print","runs":[{"text":"Return, do not print"}]},{"t":"p","runs":[{"text":"The distinction from the earlier functions lesson deserves one more pass, because it decides whether your code can be reused."}]},{"t":"code","lang":"python","label":"Python","text":"def report(rows):\n    for r in rows:\n        print(f\"{r['name']}: {r['total']}\")"},{"t":"p","runs":[{"text":"That function can do exactly one thing: write to a terminal. It cannot be tested without capturing standard output, cannot write to a file, cannot be sent over HTTP, and cannot be translated."}]},{"t":"code","lang":"python","label":"Python","text":"def format_report(rows):\n    return \"\\n\".join(\n        f\"{r['name']}: {r['total']}\" for r in rows\n    )\n\nrows = [\n    {\"name\": \"Asha\", \"total\": 42},\n    {\"name\": \"Ravi\", \"total\": 17},\n]\nprint(format_report(rows))"},{"t":"p","runs":[{"text":"Now the same function serves a terminal, a file, an email and a test, and the test is one line: "},{"text":"assert format_report([...]) == \"...\"","code":true},{"text":". Push printing to the outermost layer of the program and keep everything underneath returning values."}]},{"t":"h2","id":"returning-a-value-the-caller-must-check","runs":[{"text":"Returning a value the caller must check"}]},{"t":"p","runs":[{"text":"Three ways to signal “there was no answer”, each with a cost:"}]},{"t":"ul","items":[[{"text":"Return ","b":true},{"text":"None","b":true,"code":true},{"text":".","b":true},{"text":" Cheap, and easy to forget to check. Fine when absence is ordinary and the caller obviously handles it."}],[{"text":"Return a default.","b":true},{"text":" "},{"text":"get_price(item, default=0)","code":true},{"text":" keeps the caller simple and can hide a real failure inside an average."}],[{"text":"Raise an exception.","b":true},{"text":" Impossible to ignore, and correct when continuing would mean producing a wrong answer. The errors module covers this properly."}]]},{"t":"p","runs":[{"text":"Whichever you choose, choose it once per function and write it in the docstring. Functions that sometimes return "},{"text":"None","code":true},{"text":" and sometimes raise are the ones that produce three-in-the-morning bugs."}]},{"t":"p","runs":[{"text":"Never signal failure with a sentinel like "},{"text":"-1","code":true},{"text":" or "},{"text":"\"ERROR\"","code":true},{"text":". It has the same type as a real answer, so it flows through arithmetic and string joins undetected until the total is wrong."}]},{"t":"h2","id":"returning-early-against-a-single-exit","runs":[{"text":"Returning early against a single exit"}]},{"t":"p","runs":[{"text":"Some traditions insist on one "},{"text":"return","code":true},{"text":" per function. Python’s does not, and guard clauses are the house style. The practical test is whether a reader can see all the ways out. Four early returns in a fifteen-line function are clear. Nine returns scattered through eighty lines are not, and that function wanted splitting anyway."}]},{"t":"h2","id":"a-function-that-returns-nothing-should-say-so","runs":[{"text":"A function that returns nothing should say so"}]},{"t":"p","runs":[{"text":"If a function’s job is a side effect (writing a file, sending a request) return "},{"text":"None","code":true},{"text":" and name it with a verb: "},{"text":"save_report","code":true},{"text":", "},{"text":"send_email","code":true},{"text":", "},{"text":"delete_row","code":true},{"text":". Functions that compute get noun-ish names: "},{"text":"total","code":true},{"text":", "},{"text":"format_report","code":true},{"text":", "},{"text":"parse_date","code":true},{"text":". The convention is not decoration; it means a reader can tell from the call site whether the result matters."}]}],"check":{"question":[{"text":"A price lookup returns "},{"text":"-1","code":true},{"text":" when an item is unknown. Totals across the catalogue have been slightly low for months. What is the defect this illustrates?"}],"options":[{"text":[{"text":"The sentinel should have been 0, which is neutral in a sum and therefore safe."}],"correct":false,"tempting":[{"text":"Swaps one in-band sentinel for another; zero is silently wrong in a division or an average and still cannot be distinguished from a real price."}]},{"text":[{"text":"The failure signal has the same type as a real answer, so it flows through arithmetic undetected instead of stopping the calculation."}],"correct":true,"tempting":null},{"text":[{"text":"The function should print a warning when the item is unknown, so the operator can see the problem in the log."}],"correct":false,"tempting":[{"text":"Adds visibility without fixing the arithmetic, and pushes output into a function whose job is to compute."}]},{"text":[{"text":"Returning early from a lookup is the real problem; a single exit point would have made the bug obvious."}],"correct":false,"tempting":[{"text":"Attributes the fault to control flow style rather than to the choice of an in-band failure value."}]}],"order":[3,0,1,2],"why":null},"prev":{"slug":"scope-and-globals","title":"Where a name lives, and why the function cannot see it","minutes":8},"next":{"slug":"docstrings-and-type-hints","title":"Saying what a function expects, and what checks it","minutes":8}}}