12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

12.3. Tuples as return values 117>>> print unamemonty>>> print domainpython.org12.3 Tuples as returnvaluesStrictly speaking, a function can only return one value, but if the value is a tuple, the effect is thesameasreturningmultiplevalues. Forexample, ifyouwanttodividetwointegersandcomputethequotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute themboth at thesame time.The built-in function divmod takes two arguments and returns a tuple of two values, the quotientand remainder. You can storetheresult asatuple:>>> t = divmod(7, 3)>>> print t(2, 1)Or usetuple assignment tostoretheelements separately:>>> quot, rem = divmod(7, 3)>>> print quot2>>> print rem1Here isanexample of afunction that returns atuple:def min_max(t):return min(t), max(t)maxandminarebuilt-infunctionsthatfindthelargestandsmallestelementsofasequence. min_maxcomputes both and returnsatupleof twovalues.12.4 Variable-lengthargument tuplesFunctions can take a variable number of arguments. A parameter name that begins with * gathersarguments into atuple. For example,printalltakes any number of arguments and prints them:def printall(*args):print argsThegatherparametercanhaveanynameyoulike,butargsisconventional. Here’showthefunctionworks:>>> printall(1, 2.0, '3')(1, 2.0, '3')The complement of gather is scatter. If you have a sequence of values and you want to pass it to afunction as multiple arguments, you can use the * operator. For example, divmod takes exactly twoarguments; itdoesn’t workwithatuple:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!