COP 3035 Lecture File 04 Iteration: Looping – – – – Using while loops Major loop types and major loop tasks Multiple Termination Conditions Simulation/Modeling and introduction to using pseudo-random numbers Copyright Ann Ford Tyson 1 The Four Control Structures FLOW OF CONTROL – Sequential one after another, in order – Selection or Branching (if, if-else, if-elif) can choose between different statements – Iteration or Looping (while, for) repeat instructions over and over – Subprogram (function) perform a task when called 2 Iteration Iteration (looping): control structure which allows statements to execute repeatedly Iteration statements in Python – while – for 3 while loop most general, can implement ANY form of loop structure needed SYNTAX true or false while <expression> : <stmt block> loop body ACTION while the expression is true, execute the statement block 4 Flow of control: while false evaluate expression true execute loop body EXIT 5 while characteristics p.1 what would happen if the expression was false when the loop was first encountered? 6 while characteristics p.1a what would happen if the expression was false when the loop was first encountered? the loop body would never execute 7 while characteristics p.2 what would happen if the expression never became false ? 8 while characteristics p.2a what would happen if the expression never became false ? "infinite loop" 9 infinite loop characteristics may see same output over and over may see computer seem to "hang" to stop (Windows PC): – click on the usual X box – control-alt-delete – may need to restart 10 Did you hear about the computer scientist found dead in the shower? Sure! They thought he had been dead for days. And in his hand, he was clutching a shampoo bottle with these directions: lather rinse repeat Is that an algorithm? 11 Overview of Major Loop Types loops count-controlled iteration counter sentinel event-controlled flag 12 Overview of Major Loop Tasks loops counting event counter summing running total 13 first loop example sentinel-controlled loop executes until a particular value is read event-controlled loop (more general term) executes until some event occurs first example: sentinel-controlled, eventcontrolled, sentinel is 'Y' or 'N' 14 while: sentinel-controlled # ask user for Y or N and recover from # data entry errors # first do a priming read response = input ("Enter Y or N -> ") while (response != 'Y' and response != 'N'): response = input ("Please try again. Enter Y or N -> ") 15 first example: questions How many times does the loop body execute? zero or as many as needed What is the value of response after the loop exits? complement of expr must be true, hence (response == 'Y') or (response == 'N') 16 first example: what if questions p.1 what if we changed the and to or ? 17 first example: what if questions p.1a what if we changed the and to or ? infinite loop 18 first example: what if questions p.2 what if we forgot the priming read? 19 first example: what if questions p.2a what if we forgot the priming read? response would be uninitialized when the test expression is encountered 20 second loop example count-controlled loop executes a specified number of times a counter controls the number of iterations example: print the numbers from 1 through 100 and their squares, as in the next table notice in the code: – loop body executes 100 times – count is 101 when loop exited 21 second loop example p.2 Number ====== 1 2 3 4 . . . 98 99 100 Square ====== 1 4 9 16 . . . 9604 9801 10000 # 5 blanks # between 22 while: count-controlled # print table heading once print ("Number Square") print ("====== ======") count = 1 # initialize counter while count <= 100: square = count ** 2 print ("%5d%11d" % (count, square)) count = count + 1 # update counter 23 Now, let's look at the program In lecture we will now switch to IDLE and examine this program running This program is available from the class web site countContrLoop.py 24 second example: what if questions p.1 what if we forget to increment the counter inside the loop? 25 second example: what if questions p.1a what if we forget to increment the counter inside the loop? infinite loop, count stays 1 26 second example: what if questions p.2 what if we used "count < 100" instead? 27 second example: what if questions p.2a what if we used "count < 100" instead? OFF BY ONE error; through 99 only 28 Loops: two major semantic (logic) errors to watch for ! Infinite Loop Off by One 29 More Assignment Operators <variable> <op>= <expr> interpreter expands to <variable> = <variable> <op> <expr> where <op>= is += -= *= /= //= %= 30 More Assignment Examples i=1 j=3 i += 1 i *= j j *= i + 1 # execute in sequence translation: i = i + 1 effect: i 2 translation: i = i * j effect: i 6 translation: j = j * (i + 1) effect: j 21 31 Nested Loop Example: flag-controlled + sentinel-controlled # ask user to enter a Fahrenheit # temperature, convert it to Celcius, then # repeat as long as user wishes fahrenTemp = 0 celTemp = 0 response = "" keepGoing = True # create variables needed 32 Nested Loop Example p.2 # assume user wants to convert at least # one temperature while keepGoing: # get a temp and convert it fahrenTemp = int(input("Enter a temperature in Fahrenheit -> ")) celTemp = int (5.0 / 9.0 * (fahrenTemp - 32)) 33 Nested Loop Example p.3 print ("In Celcius that is ", celTemp) # ask if user wants to convert again print () response = input ("Do Again? Enter Y or N -> ") while (response != 'Y' and response != 'N'): response = input ("Please try again." + " Enter Y or N -> ") # reset flag keepGoing = (response == 'Y') # end of while (keepGoing) loop 34 Summing and Counting Loops Task: read scores from user and calculate mean score, where mean = sum of scores / number of scores Example data (mean == 443/5 == 88) 77 95 82 89 100 -1 88.6 as a float # sentinel, signal to stop 35 Fundamental Technique: keep a cumulative total (running sum) let sum store running total let value be what is read general summing loop pseudocode set sum to zero while ( have more values ) read a value add it to sum 36 Fundamental Technique: keep a cumulative count (running count) let count store running count let value be what is read general counting loop pseudocode set count to zero while ( have more values ) read a value add 1 to count 37 Program example (p. 1) # create constants and variables QUIT_CODE = -1 score = 0 numScores = 0 sum = 0 mean = 0 38 Program example (p. 2) # priming read score = int(input ("Enter a score (-1 to quit): ")) while score != QUIT_CODE: sum = sum + score numScores += 1 score = int(input ("Enter a score: ")) # calculate mean and print mean = sum / numScores print ("Mean is: ", mean) 39 What if we used this loop instead? # skip priming read and rearrange while ( score != QUIT_CODE) : score = int(input ("Enter a score: ")) sum = sum + score numScores += 1 sentinel would be used as the last score sum and mean would be wrong 40 Finding the maximum and minimum in a data set Why? Statistics, image processing (error detection, smoothing, etc.), game list of high scores, etc. Task: Read integers from user which represent the number of yards a football player has gained in the last 5 games he has played Find the highest and lowest yardage (ESPN will pay for this program!) 41 More about the task Example data 87 55 194 210 7 We can look at a short list and see max (210) and min (7). How does a computer do this? 42 Algorithm set min to 1st value set max to 1st value while ( have more values ) read a new value compare it to min, and reset min if needed compare it to max, and reset max if needed 43 Max/Min example (p. 1) # create constants and variables NUM_GAMES = 5 yards = 0 max = 0 min = 0 count = 1 44 Max/Min example (p. 2) # read 1st value & initialize min & max yards = int(input("Enter a yardage: ")) min = yards max = yards 45 Max/Min example (p. 3) while ( count < NUM_GAMES ) : # process next value how many iterations? yards = int(input("Enter a yardage: ")) if ( yards < min ) : min = yards elif ( yards > max ) : max = yards why? count += 1 46 Max/Min example ( p. 4) # output final results print ("Lowest was: ", min) print ("Highest was: ", max) print ("Now send bill to ESPN!") 47 Multiple Termination Conditions and Simulation Multiple Termination Conditions – while ((some condition is true) and (a second condition is true)) – alternatives: more conditions, using combinations of and, or, not, etc. 48 Loop Exercise Multiple Termination Conditions We will now switch over to this exercise and work on it live in class loopExerciseStarter.py loopExerciseSoln.py 49 Simulation Simulation – use a computer program to simulate or model a real-world process • flight simulators, playing golf, football on a computer and other games • model behavior of a business, world economy, beach erosion, hurricane tracking, etc. – can explore and test theories which cannot be tested in "real world" • ask what if questions, such as, what if we raise the prime interest rate by 1% ? 50 Random Numbers Random numbers: Examples – dice roll – lottery numbers generated by the actual number drawing – no discernable order or pattern 51 Pseudo-Random Numbers p.1 Pseudo-random numbers – appear "random" to user – e.g. simulate a dice roll in a program – computer-generated "easy-pick" lottery numbers – random plays and shuffling on a music player (like an iPod) – generated by an algorithm, so not truly random; there is a pattern 52 Programming/Mathematics Humor: Random Numbers The generation of random numbers is too important to be left to chance. -- Robert Coveyou 53 Pseudo-Random Numbers p.2 Pseudo-random numbers – Typically generated in a sequence r0, r1, r2, r3 … – Each value depends on previous value rN = some calculation using rN-1 – first value is seed 54 Example Program: A Lottery Game player starts with $10 player bets $1 each play player picks a number between 1 and 999 computer draws a number (same range) using a pseudo-random number generator if they match, player wins $500 play until either player is broke or has won once 55 Pseudocode for main loop initialize balance and won flag while (have money) and (haven't won yet) decrement balance pick a number draw a number if they match then set won flag to true print a win message else print a try again message 56 Important function usage import random this gives us access to the random module in Python module a group of standard Python library functions random.randint(1, MAX) calls this function and generates a pseudorandom number between 1 and MAX, inclusive 57 Now, let's look at the program In lecture we will now switch to IDLE and examine the lottery game program This program can be printed from the class web site lotteryGame.py 58 Next… more about loops for loop efficiency issues comparing real numbers choosing a loop for a particular task 59 Interest Example Invest money in an account paying an annual rate of interest compounded monthly. How long, in months, until the amount doubles? Example data: 1000.00 5.25 original amount annual interest rate 60 Examine this program interest.py In lecture we will now switch to IDLE and examine this program while it runs 61 Interest Example Questions p.1 What do we know is true after the loop exits? 62 Interest Example Questions p.1a What do we know is true after the loop exits? balance >= goalBalance the logical complement is true 63 Interest Example Questions p.2 What would happen if we used this instead? – while balance != goalBalance : 64 Interest Example Questions p.2a What would happen if we used this instead? – while balance != goalBalance : Probable infinite loop 65 General Programming Principle Never compare real numbers for exact equality – avoid use of == != <= >= with real numeric types (float) we would use import math and math.fabs() to make "equality" comparisons 66 Example If x and y are floats, import math if (math.fabs(x-y) < 0.0001): #fabs – float absolute or some other criterion value, treat them as equal 67 Interest Example Questions p.3 Why declare goalBalance and monthlyRate? Why not just use this? VERY inefficient items in blue are repeated for every iteration while (balance < GOAL_FACTOR * originalAmt) : balance = balance + ((annualRate / MONTHS_PER_YEAR) / 100.0 * balance) month = month + 1 68 Efficiency Note Do not put code inside a loop which should not be repeated Example: a calculation which only needs to be done once, as in the previous example 69 for loop Usage: count-controlled loops a counter controls the number of iterations 70 Examples Using a list of values for variable in [value1, value2, etc.]: stmt1 stmt2 stmt3 for num in [0, 1, 2, 3, 4]: print (num) # prints 0,1,2,3,4 71 Examples Using the range function for num in range(5): # prints 0,1,2,3,4 print(num) Using start value, end limit, step value for num in range (1, 10, 2): print (num) # prints 1,3,5,7,9 Also can count down (negative step) 72 Examine this program userSquares2.py In lecture we will now switch to IDLE and examine this program while it runs 73 recall this loop example: Number ====== 1 2 3 4 . . . 98 99 100 Square ====== 1 4 9 16 . . . 9604 9801 10000 # 5 blanks # between 74 while: count-controlled # print table heading once print ("Number Square") print ("====== ======") count = 1 # initialize counter while count <= 100: square = count ** 2 print ("%5d%11d" % (count, square)) count = count + 1 # update counter 75 using for # print table heading once print ("Number Square") print ("====== ======") for count in range(1, 101) : square = count ** 2 print ("%5d%11d" % (count, square)) initialization and update do not require separate statements 76 Nested for loops How would we generate this multiplication table? 1 2 3 4 5 ... 9 1 1 2 3 4 5 ... 9 2 2 4 6 8 10 ... 18 3 3 ... 6 9 ... 12 15 ... 27 9 9 18 27 36 45 ... 81 77 Examine this program nestedFor.py In lecture we will now switch to IDLE and examine this program while it runs 78 Odds and Ends… # you can use strings with a list for name in ["amy", "bob", "carl", "denise"]: print (name) # you can mix types in a list for item in ['A', 45, "fred"]: print (item) # you cannot use characters with range, as in # for ch in range('A', 'Z') # print (ch) # produces a syntax error 79 Choosing a loop structure p.1 Is the loop count-controlled? for usually best Is the loop event-controlled (flag, sentinel, other conditions being tested)? while Multiple termination conditions? while 80 Next … Testing and Debugging More programming, more Python! 81