11.4Returning Values
Covers IGNOU MCS-201 §11.5
Parameters bring values into a function; return sends a result out. A function that returns its result, rather than printing it, can be reused in calculations, conditions and other function calls.
The return statement
def function_name(parameters):
...
return expressionreturn expressionends the function immediately and gives the value of the expression to the caller.- Statements after an executed
returndo not run. - A function without
return, or with a barereturn, returnsNone. return a, breturns one tuple(a, b), which the caller can unpack:s, avg = stats(...).
Key takeaways
returnends the function and passes back a value.return a, breturns one tuple; unpack it withx, y = f().- Any number of
returnstatements are allowed; the first reached wins. - Without
return, a function returnsNone.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function min_max(values) that returns both the smallest and largest value of a list, and show how to call it.
Show worked answer
def min_max(values): return min(values), max(values). Call: low, high = min_max([7, 2, 9, 4]), which sets low = 2 and high = 9. The function returns one tuple (2, 9), which the assignment unpacks into the two names.