Returning Two Results at Once
In this lesson, you ported a function that hands back two results and saw why JavaScript needs an array where Python returns a tuple.
- Python’s
quote()works out the fee and the turnaround and hands both back at once withreturn fee, days. The caller unpacks them withfee, days = quote(6200). For the 6,200-word contract without the rush, the call gives the tuple(744.0, 5). - The line-by-line port keeps
return fee, days;, andconsole.log(quote(6200))logs only5, with no error: like a missing argument, the slip hides behind a believable number. That’s because JavaScript has no tuples. In Python, the comma is what builds the tuple, even without parentheses. In JavaScript, the comma is an operator: it evaluates the fee and drops it, then evaluates the days and keeps that last value. - Parentheses don’t make a tuple either:
return (fee, days);still gives5. - Python’s unpacking ports as array destructuring,
const [fee, days] = quote(6200);, the same destructuring you can write in afor...ofheader. Withquote()returning a single number, that line throwsTypeError: quote is not a function or its return value is not iterable, and the stack trace points to line 8. Unlike a missing argument, this doesn’t go quiet. quoteis a function, so it’s the message’s second cause: the return value isn’t iterable. Iterable means what it means in Python, something you can loop over, and a number isn’t. Python stops the same way:fee, days = 5raisesTypeError: cannot unpack non-iterable int object.- The real slip is back up in
quote()’sreturn, which ran without a word, so when destructuring fails, read the function’sreturnfirst. - The fix goes where the results leave the function:
return [fee, days];. The first call then logs[ 744, 5 ], and the destructuring unpacks it into the fee and the days. The fee prints as744, without Python’s.0. JavaScript numbers don’t split into integers and floats, so a whole value prints without one. - The array does the tuple’s job here, a pair read by position. Unlike a tuple, nothing stops code from changing the array later.
- When the results deserve names, where Python might reach for a dict or a named tuple, a function returns an object instead, and the caller reads each one by name. The short way to write that object comes later in this course.
Here’s the Python script’s quote() and its caller:
def quote(words):
fee = max(words * 0.12, 40)
days = 2 + words // 2000
return fee, days
print(quote(6200))
fee, days = quote(6200)
print(fee, days)