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.

64 Chapter 7. IterationThethirdlinechangesthevalueofabutdoesnotchangethevalueofb,sotheyarenolongerequal.Although multiple assignment is frequently helpful, you should use it with caution. If the values ofvariables change frequently, itcan make thecode difficult toread and debug.7.2 Updating variablesOne of the most common forms of multiple assignment is an update, where the new value of thevariable depends onthe old.x = x+1This means “get thecurrent value ofx,add one, and then updatexwiththenew value.”Ifyoutrytoupdateavariablethatdoesn’texist,yougetanerror,because<strong>Python</strong>evaluatestherightsidebefore itassigns avalue tox:>>> x = x+1NameError: name 'x' is not definedBefore you can update avariable, you have toinitializeit,usually withasimpleassignment:>>> x = 0>>> x = x+1Updating avariable byadding 1iscalled anincrement; subtracting 1iscalled a decrement.7.3 ThewhilestatementComputers are often used to automate repetitive tasks. Repeating identical or similar tasks withoutmaking errorsissomething that computers dowell and people do poorly.We have seen two programs, countdown and print_n, that use recursion to perform repetition,which is also called iteration. Because iteration is so common, <strong>Python</strong> provides several languagefeatures to make it easier. One is the for statement we saw in Section 4.2. We’ll get back to thatlater.Another isthewhilestatement. Here isaversion ofcountdownthat uses awhilestatement:def countdown(n):while n > 0:print nn = n-1print 'Blastoff!'You can almost read the while statement as if it were English. It means, “While n is greater than0, display the value of n and then reduce the value of n by 1. When you get to 0, display the wordBlastoff!”Moreformally, here isthe flow of execution forawhilestatement:1. Evaluate thecondition, yieldingTrueorFalse.

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

Saved successfully!

Ooh no, something went wrong!