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.

110 Chapter 11. Dictionariesknown[n] = resreturn resknownis a dictionary that keeps track of the Fibonacci numbers we already know. It starts with twoitems: 0maps to0and 1maps to1.Wheneverfibonacciiscalled,itchecksknown. Iftheresultisalreadythere,itcanreturnimmediately.Otherwiseithas tocompute thenew value, add ittothe dictionary, and returnit.Exercise 11.6 Run this version of fibonacci and the original with a range of parameters andcompare their runtimes.11.6 Global variablesIn the previous example, known is created outside the function, so it belongs to the special framecalled__main__. Variablesin__main__aresometimescalledglobalbecausetheycanbeaccessedfrom any function. Unlike local variables, which disappear when their function ends, global variablespersistfrom one function call tothenext.Itiscommontouseglobalvariablesforflags;thatis,booleanvariablesthatindicate(“flag”)whethera condition is true. For example, some programs use a flag named verbose to control the level ofdetail inthe output:verbose = Truedef example1():if verbose:print 'Running example1'If you try to reassign a global variable, you might be surprised. The following example is supposedtokeep trackof whether the function has been called:been_called = Falsedef example2():been_called = True# WRONGBut if you run it you will see that the value of been_called doesn’t change. The problem is thatexample2 creates a new local variable named been_called. The local variable goes away whenthefunction ends, and has noeffect on theglobal variable.To reassign a global variable inside a function you have to declare the global variable before youuseit:been_called = Falsedef example2():global been_calledbeen_called = TrueThe global statement tells the interpreter something like, “In this function, when I saybeen_called,Imean the global variable; don’t create alocal one.”Here’s an example that triestoupdate aglobal variable:

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

Saved successfully!

Ooh no, something went wrong!