12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

66 Chapter 7. Iterationbreakprint lineprint 'Done!'The loop condition isTrue,which isalways true, sotheloop runs until ithitsthe break statement.Each time through, it prompts the user with an angle bracket. If the user types done, the breakstatement exits the loop. Otherwise the program echoes whatever the user types and goes back tothetop of theloop. Here’s asample run:> not donenot done> doneDone!This way of writing while loops is common because you can check the condition anywhere inthe loop (not just at the top) and you can express the stop condition affirmatively (“stop when thishappens”) rather than negatively (“keep going until that happens.”).7.5 Square rootsLoops are often used in programs that compute numerical results by starting with an approximateanswer and iteratively improving it.For example, one way of computing square roots is Newton’s method. Suppose that you want toknowthesquarerootofa. Ifyoustartwithalmostanyestimate,x,youcancomputeabetterestimatewiththefollowing formula:For example, ifais4and x is3:y= x+a/x2>>> a = 4.0>>> x = 3.0>>> y = (x + a/x) / 2>>> print y2.16666666667Which is closer to the correct answer ( √ 4=2). If we repeat the process with the new estimate, itgets even closer:>>> x = y>>> y = (x + a/x) / 2>>> print y2.00641025641Afterafew more updates, theestimateisalmost exact:>>> x = y>>> y = (x + a/x) / 2>>> print y

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

Saved successfully!

Ooh no, something went wrong!