✓ While loop
def countdown(n): while n > 0: print n n = n-1 #output: 5,4,3,2,1 def sequence(n): while n != 1: print n, if n%2 == 0: n = n/2 else: n = n*3+1; #output: 3, 10, 5, 16, 8, 4, 2, 1
✓ Break – Break statement is used to jump out of the loop.
while True: line = raw_input('> ') if line == 'done': break; print line
✓ Square roots – Loops can be also used in programs that compute numerical results by starting with an approximate answer and iteratively improving it. Square root can be estimated using Newton’s method.
✓ Newton’s method:
f(xn) = xn2-S
xn+1 = xn – f(xn)/f’(xn)
xn+1 = xn – xn2-S/ 2xn
xn+1 = (xn + S/ xn)/2
>>> a = 4.0 # square root of 4.0 needs to estimated >>> x = 3.0 # first approximate value is 3.0 >>> y = (x + a/x) / 2 >>> print y 2.16666666667 >>> x = y # second approximate value >>> y = (x + a/x) / 2 >>> print y 2.00641025641 # third approximate value # accurate value can esimate by loop while True: print x y = (x + a/x) / 2 if abs(y-x) < epsilon: break x = y
Estimate 1/d using the newton’s method.
f(xn) = 1/xn – d
f’(xn) = -1/xn2
xn+1 = xn- (1/xn – d )/(-1/xn2)
xn+1 = xn(2-dxn)