control structure
play

Control structure: Repetition - Part 2 01204111 Computers and - PowerPoint PPT Presentation

Control structure: Repetition - Part 2 01204111 Computers and Programming Cha hale lermsak Cha hatdokmaip ipra rai De Depart rtment of of Com omputer r Eng ngineerin ing Kas asetsart Uni niversity Revised 2018-07-16 Cliparts are


  1. Control structure: Repetition - Part 2 01204111 Computers and Programming Cha hale lermsak Cha hatdokmaip ipra rai De Depart rtment of of Com omputer r Eng ngineerin ing Kas asetsart Uni niversity Revised 2018-07-16 Cliparts are taken from http://openclipart.org

  2. 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

  3. 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 : F mor ore items in code_block sequence ? The number of times the code_block T is executed is precisely the number variable = = ne next xt it item of items in the sequence. code_b _blo lock Therefore the for -loop is also called the definite loop because it repeats its loop body a definite number of times. 3

  4. 4

  5. Fahrenheit-to 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

  6. Fahrenheit-to 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 than the for-loop: requires only integer arguments but 0.5 is not an integer. Conditional loops 6

  7. 7

  8. The while Statement Pyton Syntax Semantics while condition : F code_block condit itio ion T • condition is a Boolean expression. code_block • code_block is, as usual, an indented sequence of one or more statements. 8

  9. Example F n > 0 def countdown (n): while n > 0: T print(n) print(n) n = n-1 print("Go!") n = n-1 >>> countdown(4) 4 3 print("Go!") 2 1 Go! This means, in this case, >>> countdown(0) that the loop body doesn't Go! get executed at all. Why? 9

  10. 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

  11. 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 before the first iteration. F 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 iteration: calcutate cel from fah , print fah,cel then print a line of the table . fah = fah+ step Increment fah by step , to ready fah for the next iteration. 11

  12. 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

  13. fah_to_cel() version 2 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. 14

  15. 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 , because the step is positive and >>> fah_to_cel(50, 40, 2.5) the start 50 already exceeds Fahrenheit Celcius 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

  16. 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 ---------- ------- empty table. But what you see is … -41152.50 -22880.28 30.00 -1.11 -41155.00 -22881.67 27.50 -2.50 one minute -41157.50 -22883.06 25.00 -3.89 -41160.00 -22884.44 later 22.50 -5.28 -41162.50 -22885.83 20.00 -6.67 -41165.00 -22887.22 17.50 -8.06 -41167.50 -22888.61 The program is still running -41170.00 -22890.00 15.00 -9.44 indefinitely, so you decide to -41172.50 -22891.39 12.50 -10.83 hit Ctrl-C to stop the program. -41175.00 -22892.78 10.00 -12.22 -41177.50 -22894.17 7.50 -13.61 -41180.00 -22895.56 5.00 -15.00 -41182.50 -22896.94 You have 2.50 -16.39 -41185.00 -22898.33 0.00 -17.78 encountered -41187.50 -22899.72 -2.50 -19.17 -41190.00 -22901.11 an infinite loop! -41192.50 -22902.50 -5.00 -20.56 KeyboardInterrupt -7.50 -21.94 >>> -10.00 -23.33 16

  17. 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 to be false for the loop to exit. cel = (5/9)*(fah-32) Since the third argument step is -2.5 , which is negative , fah always becomes print fah,cel smaller in the next iteration. Therefore the ever-decreasing fah fah = fah+ step will never reach 40 , so fah < 40 is always true and the loop will never exit. Thus the infinite loop . 17

  18. So there are bugs in fah_to_cel() version 2 We should have seen a table >>> fah_to_cel(50, 40, -0.5) running from 50 downto 40, Fahrenheit Celcius decremented by 0.5, rather ---------- ------- than this empty table. ---------- ------- We should have seen an empty >>> fah_to_cel(30, 40, -2.5) table rather than this endless Fahrenheit Celcius output of an infinite loop. ---------- ------- 30.00 -1.11 So our loop algorithm for version 2 27.50 -2.50 works OK for positive steps but 25.00 -3.89 does not work correctly for 22.50 -5.28 -41177.50 -22894.17 20.00 -6.67 negative steps. -41180.00 -22895.56 17.50 -8.06 -41182.50 -22896.94 Can you modify 15.00 -9.44 -41185.00 -22898.33 fah_to_cel() to eliminate 12.50 -10.83 -41187.50 -22899.72 10.00 -12.22 these bugs? -41190.00 -22901.11 7.50 -13.61 -41192.50 -22902.50 An E-lab task will do. อิอิ KeyboardInterrupt >>> 18

  19. 19

  20. 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

  21. 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

  22. Counting-Loop Pattern translated into a while loop Initialize the counter a variable F counter 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

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend