Another For Loop Implementation def sqrtx x floatx L x for k in range5 L L xL2

# Another for loop implementation def sqrtx x floatx l

This preview shows page 50 - 56 out of 56 pages.

Another For-Loop Implementation def sqrt(x): x = float(x) L = x for k in range(5): L = (L + x/L)/2 return L def sqrt(x,N=5): x = float(x) L = x for k in range(N): L = (L + x/L)/2 return L Sample Call: y = sqrt(12345,20 ) The optional argument allows you to determine the number of iterations. Now Let Us Look at Graphics Procedures and For Loops Recall DrawRect DrawRect(xc,yc,s,s,FillColor=RED) DrawRect(xc,yc,s,s,FillColor=WHITE) This will draw a red square with side s and center (xc,yc): This will draw a white square with side s and center (xc,yc): Let’s Write a Procedure that Can Draw a Checkered Row Assume n squares each with side s. Assume (x0,y0) is the center of the leftmost square. Let c1 and c2 be the Colors of the first and second square Solution def DrawRow(x0,y0,s,n,c1,c2): # Center of next square is (xc,yc) xc = x0, yc = y0 for k in range(n): % Draw the kth square if k%2==0: DrawRect(xc,yc,s,s,FillColor=c1) else: DrawRect(xc,yc,s,s,FillColor=c2) xc = xc+s Now Let’s Draw This This Draws an 8x8 Checker Board y0 = -4; x0 = -3.5; n = 8; s = 1 #(x0,y0) is the center of the leftmost # square in the next row to draw for k in range(n): # Draw the kth row if k%2==0: DrawRow(x0,y0,s,n,RED,WHITE) else: DrawRow(x0,y0,s,n,WHITE,RED) # The next row is s units higher y0 = y0+s #### You've reached the end of your free preview.

Want to read all 56 pages?

• Fall '19
• Summation, leftmost square
• • • 