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.

3.10. Stack diagrams 23Thisfunctiontakestwoarguments,concatenatesthem,andprintstheresulttwice. Hereisanexamplethatusesit:>>> line1 = 'Bing tiddle '>>> line2 = 'tiddle bang.'>>> cat_twice(line1, line2)Bing tiddle tiddle bang.Bing tiddle tiddle bang.Whencat_twiceterminates,thevariablecatisdestroyed. Ifwetrytoprintit,wegetanexception:>>> print catNameError: name 'cat' is not definedParameters are alsolocal. For example, outsideprint_twice,thereisno such thingasbruce.3.10 StackdiagramsTokeeptrackofwhichvariablescanbeusedwhere,itissometimesusefultodrawastackdiagram.Likestatediagrams,stackdiagramsshowthevalueofeachvariable,buttheyalsoshowthefunctioneach variable belongs to.Eachfunctionisrepresentedbyaframe. Aframeisaboxwiththenameofafunctionbesideitandthe parameters and variables of the function inside it. The stack diagram for the previous examplelooks like this:__main__line1line2’Bing tiddle ’’tiddle bang.’cat_twicepart1part2cat’Bing tiddle ’’tiddle bang.’’Bing tiddle tiddle bang.’print_twicebruce’Bing tiddle tiddle bang.’The frames are arranged in a stack that indicates which function called which, and so on. In thisexample,print_twicewas called bycat_twice,andcat_twicewas called by__main__,whichis a special name for the topmost frame. When you create a variable outside of any function, itbelongs to__main__.Each parameter refers to the same value as its corresponding argument. So, part1 has the samevalue asline1,part2has thesamevalue asline2,andbrucehas the samevalue ascat.Ifanerroroccursduringafunctioncall,<strong>Python</strong>printsthenameofthefunction,andthenameofthefunction that called it,and thename of the function that called that, all theway back to__main__.For example, ifyou trytoaccesscatfrom withinprint_twice,you get aNameError:

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

Saved successfully!

Ooh no, something went wrong!