Control Structure: Repetition - Part 2 01204111 Computers and Programming
Total Page:16
File Type:pdf, Size:1020Kb
Control structure: Repetition - Part 2 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Revised 2018-07-16 Outline ➢Definite Loops : A Quick Review ➢Conditional Loops : The while Statement ➢A Logical Bug : Infinite Loops ➢A Common Loop Pattern : Counting Loops ➢A Common Loop Pattern : Interactive Loops ➢A Common Loop Pattern : Sentinel Loops ➢One More Example : Finding the Maximum 2 Definite Loops : A Quick Review • We've already learned that the Python for- statement provides a simple kind of loops that iterate through a sequence of values. for variable in sequence : code_block more items in F sequence ? The number of times the code_block T is executed is precisely the number variable = next item of items in the sequence. Therefore the for-loop is also code_block called the definite loop because it repeats its loop body a definite number of times. 3 4 Fahrenheit-to-Celcius Table Revisited def fah_to_cel(start, end, step): print(f"{'Fahrenheit':>12}{'Celcius':>12}") print(f"{'----------':>12}{'-------':>12}") for fah in range(start, end, step): cel = (5/9)*(fah-32) print(f"{fah:12}{cel:12.1f}") print(f"{'----------':>12}{'-------':>12}") >>> fah_to_cel(40, 50, 3) >>> fah_to_cel(100,32,-20) Fahrenheit Celcius Fahrenheit Celcius ---------- ------- ---------- ------- 40 4.4 100 37.8 43 6.1 80 26.7 46 7.8 60 15.6 49 9.4 40 4.4 ---------- ------- ---------- ------- 5 Fahrenheit-to-Celcius Table Revisited What if we want to print the conversion table ranging from 40 F upto 50 F, progressing with the step of 0.5 F? >>> fah_to_cel(40, 50, 0.5) Fahrenheit Celcius ---------- ------- File "C:\Users\ccd\PyFi\fah2cel.py", line 5, in fah_to_cel for fah in range(start, end, step): TypeError: 'float' object cannot be interpreted as an integer We need another kind of The result is a run-time error loops that is more flexible because the range() function requires only integer arguments than the for-loop: but 0.5 is not an integer. Conditional loops 6 7 The while Statement Pyton Syntax Semantics while condition: F code_block condition T •condition is a Boolean expression. code_block •code_block is, as usual, an indented sequence of one or more statements. 8 Example F def countdown(n): n > 0 while n > 0: T print(n) print(n) n = n-1 print("Go!") n = n-1 >>> countdown(4) 4 3 2 print("Go!") 1 Go! >>> countdown(0) This means, in this case, Go! that the loop body doesn't get executed at all. Why? 9 fah_to_cel() : a more flexible version Let's try to use the while statement to make fractional steps possible. >>> fah_to_cel(40, 50, 2.5) We need a loop Fahrenheit Celcius mechanism more ---------- ------- flexible than the 40.00 4.44 for-loop. 42.50 5.83 45.00 7.22 47.50 8.61 ---------- ------- >>> 10 fah_to_cel() : A Conditional-Loop Algorithm We devise a conditional-loop algorithm for the function fah_to_cel(). fah = start Set fah to the value of start F before the first iteration. fah < end The condition fah < end is used to T decide whether to execute another iteration or exit the loop. cel = (5/9)*(fah-32) Computation to be done for each print fah,cel iteration: calcutate cel from fah, then print a line of the table. fah = fah+step Increment fah by step, to ready fah for the next iteration. 11 fah_to_cel() : From Algorithm to Code fah = start fah = start F while fah < end: fah<end cel = (5/9)*(fah-32) T print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step cel = (5/9)*(fah-32) print fah,cel fah = fah+step The conditional loop can be easily implemented by the while statement 12 fah_to_cel() version 2 : finished def fah_to_cel(start, end, step): # version 2 print(f"{'Fahrenheit':>12}{'Celcius':>12}") print(f"{'----------':>12}{'-------':>12}") fah = start while fah < end: cel = (5/9)*(fah-32) print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step print(f"{'----------':>12}{'-------':>12}") >>> fah_to_cel(40, 50, 2.5) >>> fah_to_cel(40, 50, 3) Fahrenheit Celcius Fahrenheit Celcius ---------- ------- ---------- ------- 40.00 4.44 40.00 4.44 Works fine 42.50 5.83 43.00 6.11 when step 45.00 7.22 46.00 7.78 is an integer 47.50 8.61 49.00 9.44 ---------- ------- ---------- ------- 13 14 fah_to_cel():Bugs or Features? • Some values of the arguments start, stop, and step produce strange outputs. Are they normal, or special features, or bugs? The output is really sensible, so should be considered normal, >>> fah_to_cel(50, 40, 2.5) because the step is positive and Fahrenheit Celcius the start 50 already exceeds ---------- ------- the stop 40. ---------- ------- The output is not sensible, so should be considered a bug, >>> fah_to_cel(50, 40, -0.5) because the step is negative Fahrenheit Celcius so we'd rather see a table ---------- ------- running from 50 downto 40. ---------- ------- Can you modify fah_to_cel() to fix this? 15 fah_to_cel():Bugs or Features? 30 downto 40, decremented by >>> fah_to_cel(30, 40, -2.5) 2.5. Since start is already less Fahrenheit Celcius ---------- ------- than stop, you'd expect to see an 30.00 -1.11 -41152.50empty table. -22880.28 But what you see is … -41155.00 -22881.67 27.50 -2.50 -41157.50 -22883.06 one minute 25.00 -3.89 -41160.00 -22884.44 22.50 -5.28 -41162.50 -22885.83 later 20.00 -6.67 -41165.00 -22887.22 17.50 -8.06 -41167.50 -22888.61 15.00 -9.44 -41170.00The program-22890.00 is still running 12.50 -10.83 -41172.50indefinitely, -22891.39 so you decide to 10.00 -12.22 -41175.00hit Ctrl -22892.78-C to stop the program. -41177.50 -22894.17 7.50 -13.61 -41180.00 -22895.56 5.00 -15.00 -41182.50 -22896.94 2.50 -16.39 -41185.00 -22898.33 You have 0.00 -17.78 -41187.50 -22899.72 encountered -2.50 -19.17 -41190.00 -22901.11 -5.00 -20.56 -41192.50 -22902.50 an infinite loop! -7.50 -21.94 KeyboardInterrupt >>> -10.00 -23.33 16 How does the infinite loop happen? The call fah_to_cel(30, 40, -2.5) should have produced an empty table, so the infinite loop is obviously a bug. What's wrong with our loop algorithm? fah = start Since the first argument start is 30, F fah is 30 before entering the loop. fah<end Since the second argument end T is 40, the condition fah < 40 has cel = (5/9)*(fah-32) to be false for the loop to exit. Since the third argument step is -2.5, print fah,cel which is negative, fah always becomes smaller in the next iteration. fah = fah+step Therefore the ever-decreasing fah will never reach 40, so fah < 40 is always true and the loop will never exit. Thus the infinite loop. 17 So there are bugs in fah_to_cel() version 2 >>> fah_to_cel(50, 40, -0.5) We should have seen a table Fahrenheit Celcius running from 50 downto 40, ---------- ------- decremented by 0.5, rather ---------- ------- than this empty table. >>> fah_to_cel(30, 40, -2.5) We should have seen an empty Fahrenheit Celcius table rather than this endless ---------- ------- output of an infinite loop. 30.00 -1.11 27.50 -2.50 So our loop algorithm for version 2 25.00 -3.89 works OK for positive steps but 22.50 -5.28 does not work correctly for 20.00-41177.50 - 6.67-22894.17 -41180.00 -22895.56 negative steps. 17.50 -8.06 -41182.50 -22896.94 15.00-41185.00 - 9.44-22898.33 Can you modify 12.50-41187.50 - 10.83 -22899.72 fah_to_cel() to eliminate 10.00-41190.00 - 12.22 -22901.11 these bugs? 7.50-41192.50 - 13.61 -22902.50 KeyboardInterrupt An E-lab task will do. อิอิ >>> 18 19 Common Loop Patterns ❖ Conditional loops as realized in the Python while statement allows for many common loop patterns frequently used in programs: ▪ Counting loops (or counter-controlled loops) ▪ Interactive loops ▪ Sentinel loops ▪ Loop and a half ▪ Post-test loops ▪ Nested loops 20 Counting Loops ➢ Counting loops (also called counter-controlled loops) are one of the most frequently used loop patterns in programming. ➢ A counting loop uses a counter variable to control the number of times the loop will repeat. ➢ How many times the loop will repeat can be easily predicted before the loop starts. 21 Counting-Loop Pattern translated into a while loop Initialize the counter a variable counter F Initialize the counter is within the while counter is within the limit: limit? T Some computations Some computations Update the counter Update the counter may or may not use the counter variable in the computations 22 fah_to_cel() version 2 actually uses a counting loop. Initialize the counter fah is while counter is within the limit : the counter Some computations variable Update the counter fah = start while fah < end : cel = (5/9)*(fah-32) print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step 23 factorial(n) revisited We have once used a for-loop to implement an accumulating algorithm that computes the factorial of n. o result = 1 def factorial(n): o result = result*n result = 1 o result = result*(n-1) o result = result*(n-2) for i in range(n,1,-1): o ... result = result*i o result = result*result*22 return result o return result This accumulating algorithm can also be easily implemented by using a counting loop. 24 A Counting Loop for factorial(n) We use the variable count as o result = 1 the counter that holds these o result = result*result n* n successive values: n, n-1, …, 2 o result = result*result (n* -(n1)-1) So count is initialized to n o result = result*result (n* -(n2)-2) before entering the loop.