Presentation is loading. Please wait.

Presentation is loading. Please wait.

5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.

Similar presentations


Presentation on theme: "5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming."— Presentation transcript:

1 5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming

2 5-2 While-statements  A while-statement is a loop that enables a program to execute code repeatedly.  The while-statement has the form: while expression : body a sequence of statements (the loop body)  To execute this while-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body and then repeat from step 1 3. If the result was False, exit the loop.

3 5-3 Example: computing a square root (1)  Newton’s iterative algorithm to compute the square root of x: –Choose an initial estimate by setting r = 1.0 (say). –If r 2 is not approximately equal to x, improve the estimate by setting r = ½(r + x/r), and repeat. –If r 2 is approximately equal to x, the answer is r.  Let us take “r 2 is approximately equal to x” to mean that the relative difference between r 2 and x is less than 10 –4.

4 5-4 Example: computing a square root (2)  This function uses Newton’s algorithm: def square_root (x): # Return the square root of the positive number x. r = 1.0 while abs(x/r**2 – 1) > 0.0001: r = 0.5 * (r + x/r) return r

5 5-5 Example: computing a GCD (1)  Euclid’s iterative algorithm to compute the greatest common divisor of positive integers m and n: –Set p = m and q = n. –If p is not a multiple of q, note the remainder, set p = q, set q = remainder, and repeat. –If p is a multiple of q, the answer is q.

6 5-6 Example: computing a GCD (2)  This function uses Euclid’s algorithm: def gcd (m, n): # Return the greatest common divisor of m and n. p = m q = n r = p % q while r != 0: p = q q = r r = p % q return q

7 5-7 Example: command-line program (1)  Requirements: –The program must accept a sequence of commands, each entered by the user in response to a suitable prompt. –The program must act on the valid commands “duck” and “dive”. –The program must reject any invalid command. –The program must terminate on the empty command “”.

8 5-8 Example: command-line program (2)  Possible output and input: Command? dive … Command? duck … Command? dunk - invalid command! Command? dive … Command? - terminated. output from the “dive” command output from the “duck” command

9 5-9 Example: command-line program (3)  Outline of the command-line program: done = False while not done: com = raw_input('Command? ') if com == 'duck': duck() elif com == 'dive': dive() elif com: print '- invalid command!' else: print '- terminated.' done = True

10 5-10 Example: printing a table (1)  Suppose that we want a program to tabulate GCDs, e.g.: Table of GCDs 2 3 4 5 6 2 2 1 2 1 2 3 1 3 1 1 3 4 2 1 4 1 2 5 1 1 1 5 1 6 2 3 2 1 6

11 5-11 Example: printing a table (2)  Tabulation program: def tabulate (low, high): # Tabulate the GCD of every pair of integers in the # range low … high. print_heading(low, high) m = low while m <= high: print_row (m, low, high) m += 1

12 5-12 Example: printing a table (3)  Tabulation program (continued): def print_heading (low, high): # Print column headings in the range low … high. print 'Table of GCDs' print '\t', n = low while n <= high: print n, '\t', n += 1 print prints a tab character, not followed by a line break prints a blank line

13 5-13 Example: printing a table (4)  Tabulation program (continued): def print_row (m, low, high): # Print a row of GCDs of m and integers in the # range low … high. print m, '\t', n = low while n <= high: print gcd(m, n), '\t', n += 1

14 5-14 Invariants  An invariant is a proposition that is always true at a particular point in a program or algorithm.  An invariant may be expressed in formal logic, in precise English, or by other means.  E.g.: if n > 0: m = n m = 2*m … n > 0 n > 0 and m > 0 n > 0 and m > 0 and m is even

15 5-15 Designing loops (1)  Schematic for a while-loop: loop prelude while loop condition : loop body loop postlude  The loop prelude consists of statements that prepare for the loop (e.g., by initialising variables).  The loop postlude consists of statements that use the result(s) of the loop.

16 5-16 Designing loops (2)  Formulate a loop invariant. This is an invariant that will be true before and after every iteration of the loop body.  The loop prelude must ensure that the loop invariant is initially true.  At the start of the loop body, both the loop invariant and the loop condition will be true. The loop body must ensure that the loop invariant is true at the end.  At the start of the loop postlude, the loop invaria- nt will be true but the loop condition will be false. even if it is temporarily false in the middle

17 5-17 Example: factorial function (1)  Outline of a factorial function: def fac (n): … return f f = n!  The code “…” must ensure that f = n!. But how?  Idea: successively compute 1!, 2!, 3!,..., n!.

18 5-18 Example: factorial function (2)  Introduce a loop in which p = 1, 2, 3,..., n. The loop invariant will be f = p!: def fac (n): p = 1 … while p != n: p = p+1 … return f f = p!f = p! and p ≠ nf = p!f = p! and p = n  Note that f = p! and p = n implies f = n!.

19 5-19 Example: factorial function (3)  The loop prelude sets p = 1. To establish the loop invariant f = p!, set f = 1: def fac (n): p = 1 f = 1 while p != n: p = p+1 … return f f = p! f = p! and p ≠ n f = p! f = p! and p = n

20 5-20 Example: factorial function (4)  The loop body increments p by 1. To re-establish the loop invariant f = p!, multiply f by p: def fac (n): p = 1 f = 1 while p != n: p = p+1 f = f*p return f f = p! f = p! and p ≠ n f = p! f = p! and p = n since p! = p × (p –1)!


Download ppt "5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming."

Similar presentations


Ads by Google