380 likes | 395 Views
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING. Jehan-François Pâris jfparis@uh.edu Fall 2017. THE ONLINE BOOK CHAPTER VIII MORE ABOUT ITERATIONS. Motivation. We will learn to control better our iterations while. How much did I spend today?.
E N D
COSC 1306COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris jfparis@uh.edu Fall 2017
Motivation • We will learn to control better our iterations • while
How much did I spend today? expenses = [ 17.95, 15.95, 3.99, 5.99]total = 0for item in expenses : total += item print("Total: %.2f" % total)
Letting user enter the expenses total = 0for i in range(0, 4) : item = float(input("Enter amount: ")) total += item print("Total: %.2f" % total) Only works if we know how ahead of time howmany purchases we made that day
A more general solution n = int(input("How many purchases: ")) total = 0for i in range(0, n) : item = float(input("Enter amount: ")) total += item print("Total: %.2f" % total) User must still count manually the number of purchases
The while loop • while CONDITION : STATEMENTS • Will repeat STATEMENTSas long asCONDITION is True • Note • The colon • The indentation
The while loop while condition : something while stain : keep_washing True condition False something Go back!
while and for • While loops: • Gives more control to the user • Will result in an infinite loop if while contion remains unchanged • For loops: • Simpler and safer • Leaves the user with much less control
How much did I spend today? • Will let the user indicate end of inputs by entering a zero value • "Enter an item or zero when done"
The program total = 0notDone = Truewhile notDone: item = float(input("Enter amount: ")) if amount != 0 : total += item else : notDone = False print("Total: %.2f" % total)
Explanations total = 0notDone = Truewhile notDone: item = float(input("Enter amount: ")) if amount != 0 : total += item else : notDone = False print("Total: %.2f" % total) Initialize accumulator andwhile condition Test Keep going No more iterations
Back to our roots def mysqrt(number) : root = number/2 for i in range(10) : inverse = number/root root = (root + inverse)/2 return root • We always do 10 iterations • We should stop when we have the rightrelative precision • |root – inverse|/root < eps
A better solution def mysqrt(number) : eps = 1E-10 root = number/2 done = False while not done : inverse = number/root root = (root + inverse)/2 if abs(root - inverse)/root < eps : done = True return root # outside the while!
Why the relative error? • Because it is the one that matters • One cm matters when you drill a hole • One meter matters much less when you compute the distance between two big cities • … • One milligram matters for some drugs • One kilogram matters much less when you order a ton of dirt.
A missing construct • Python has no equivalent to the do-while construct of C, C++ and Java • do { STATEMENTS} while(CONDITION); • Same is true for Ruby but Lua has • repeat STATEMENTSuntil CONDITION
Back to the turtles • Random walk STOP
The rules • Turtle starts at center of canvas • Randomly decide to turn 90o right or left • Walks 50 steps • Repeats above steps until it hits a border of the canvas The main idea is that turtle motions are unpredictable
A better set of rules • Turtle starts at center of canvas • Randomly decide to turn 90o right or left • Walks 50 steps • Repeats above steps while it remains inside the canvas
Pseudocode • While the turtle is still in the window : • generate a random integer between 0 and 1 • if the number == 0 (heads): • turn left • else: • turn right • move the turtle forward 50
Checking if the turtle is inside (I) def isInScreen(wn,t): leftBound = -(wn.window_width()/2) rightBound = wn.window_width()/2 topBound = wn.window_height()/ 2 bottomBound = -(wn.window_height()/2) turtleX = t.xcor() turtleY = t.ycor()
Checking if the turtle is inside (II) stillIn = True if turtleX > rightBound or turtleX < leftBound: stillIn = False if turtleY > topBound or turtleY < bottomBound: stillIn = False return stillIn
Another way to write it (II) if turtleX > rightBound or turtleX < leftBound or topBound or turtleY < bottomBound : return False else : return True
The program (I) import random import turtle def isInScreen(w,t): … t = turtle.Turtle() wn = turtle.Screen() t.shape('turtle')
The program (II) while isInScreen(wn, t) : coin = random.randrange(0, 2) # !!! if coin == 0 : t.left(90) else : t.right(90) t.forward(50) wn.exitonclick()
The old art of printing tables • Can use tabs ("\t") to align table columns • Works well with fixed-fixed size fonts • Causes surprises with other fonts • Technique was widely used when computers printed listings • Were consulted off-line
A half-spirited example # Table of squares of 2 print("n", '\t', "2**n") #table headings print("---", '\t', "-----") for x in range(13): # create entries print(x, '\t', 2**x)
The outcome • n 2**n--- -----0 11 22 43 84 165 326 64…
Two-dimensional iterations • Images are represented on computers as two-dimensional arrays of pixels
Notations (I) • each pixel is denoted by its (x, y) coordinates 0 1 2 c m 01 r n
Notations (II) • Pixel 0, 0 is at top left corner 0 1 2 c m 01 r n
Notations (II) • Pixel m, n is at bottom right corner 0 1 2 c m 01 r n
Notations (III) • Pixel c ,r is blue 0 1 2 c m 01 r n
Pixel colors • The color of a pixel is defined by the intensity of its three RGB components on a scale of 0 to 255 • Red: 0 to 255 • Green: 0 to 255 • Blue: 0 to 255 • 0 means no luminance • 255 means maximum luminance 255 can be represented with 8 bits
Learning more • The rest of the chapter teaches you how to manipulate images but you have to • Download the module cImage.py from GitHub • Leave it in the same folder as your programs