1 3 4 Control Structures 3 control structures

  • Slides: 39
Download presentation
1 3. 4 Control Structures • 3 control structures – Sequential structure • Built

1 3. 4 Control Structures • 3 control structures – Sequential structure • Built into Python – Selection structure • The if statement • The if/else statement – Repetition structure • The while repetition structure • The for repetition structure 2002 Prentice Hall. All rights reserved.

2 Sequence Control Structure add grade to total = total + grade; add 1

2 Sequence Control Structure add grade to total = total + grade; add 1 to counter = counter + 1; Fig. 3. 1 Sequence structure flowchart with pseudo code. 2002 Prentice Hall. All rights reserved.

3 if Selection Structure true Grade >= 60 print “Passed” false Fig. 3. 3

3 if Selection Structure true Grade >= 60 print “Passed” false Fig. 3. 3 if single-selection structure flowchart. 2002 Prentice Hall. All rights reserved.

4 if/else Structure false true Grade >= 60 print “Failed” Fig. 3. 4 if/else

4 if/else Structure false true Grade >= 60 print “Failed” Fig. 3. 4 if/else double-selection structure flowchart. 2002 Prentice Hall. All rights reserved. print “Passed”

5 if/else Selection Structure if statement condition a true case a action(s) false first

5 if/else Selection Structure if statement condition a true case a action(s) false first elif statement true condition b case b action(s) false. . . last elif statement true condition z false else statement Fig. 3. 5 default action(s) if/else multiple-selection structure. 2002 Prentice Hall. All rights reserved. case z action(s)

6 Example with Python code # get price from user and convert it into

6 Example with Python code # get price from user and convert it into a float: price = float( raw_input(“Enter the price of one tomato: “)) if price < 1: s = “That’s cheap, buy a lot!” elif price < 3: s = “Okay, buy a few” else: s = “Too much, buy some carrots instead” print s 2002 Prentice Hall. All rights reserved.

7 Expression values? Python 2. 2 b 2 (#26, Nov 16 Type "help", "copyright",

7 Expression values? Python 2. 2 b 2 (#26, Nov 16 Type "help", "copyright", >>> if 0: . . . print "0 is true". . . else: . . . print "0 is false". . . 0 is false >>> if 1: . . . print "non-zero is. . . non-zero is true >>> if -1: . . . print "non-zero is. . . non-zero is true >>> print 2 < 3 1 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 "credits" or "license" for more information. true" Expressions have integer values. No true, false like in Java. 0 is false, non-0 is true. 2002 Prentice Hall. All rights reserved.

8 3. 16 Logical Operators • Operators – and • Binary. Evaluates to true

8 3. 16 Logical Operators • Operators – and • Binary. Evaluates to true if both expressions are true – or • Binary. Evaluates to true if at least one expression is true – not • Unary. Returns true if the expression is false Compare with &&, || and ! in Java 2002 Prentice Hall. All rights reserved.

9 Logical operators and, or, not if gender == “female” and age >= 65:

9 Logical operators and, or, not if gender == “female” and age >= 65: seniorfemales = seniorfemales + 1 if iq > 250 or iq < 20: strangevalues = strangevalues + 1 if not found_what_we_need: print “didn’t find item” # NB: can also use != if i != j: print “Different values” 2002 Prentice Hall. All rights reserved.

10 3. 11 Augmented Assignment Symbols • Augmented addition assignment symbols – x =

10 3. 11 Augmented Assignment Symbols • Augmented addition assignment symbols – x = x + 5 is the same as x += 5 – Can’t use ++ like in Java! • Other math signs – The same rule applies to any other mathematical symbol *, **, /, % 2002 Prentice Hall. All rights reserved.

11 3. 11 Augmented Assignment Symbols 2002 Prentice Hall. All rights reserved.

11 3. 11 Augmented Assignment Symbols 2002 Prentice Hall. All rights reserved.

12 Keywords Can’t use as identifiers 2002 Prentice Hall. All rights reserved.

12 Keywords Can’t use as identifiers 2002 Prentice Hall. All rights reserved.

13 keyword pass : do nothing Python 2. 2 b 2 (#26, Nov 16

13 keyword pass : do nothing Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> if 1 < 2: . . . pass . . . Sometimes useful, e. g. during development: if a <= 5 and c <= 5: print “Oh no, both below 5! Fix problem” if a > 5 and c <= 5: pass # figure out what to do later if a <= 5 and c > 5: pass # figure out what to do later if a > 5 and c > 5: pass 2002 Prentice Hall. All rights reserved. # figure out what to do later

14 3. 7 while Repetition Structure • Repetition Structures – Allow a program to

14 3. 7 while Repetition Structure • Repetition Structures – Allow a program to repeat an action while a condition is true • Using while Repetition – Action(s) contained within the body of the loop – Condition should evaluate to false at some point • Otherwise infinite loop and program hangs 2002 Prentice Hall. All rights reserved.

15 3. 7 while Repetition Structure true Product <= 1000 Product = 2 *

15 3. 7 while Repetition Structure true Product <= 1000 Product = 2 * product false Fig. 3. 8 while repetition structure flowchart. 2002 Prentice Hall. All rights reserved.

3. 8 Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) • Counter controlled repetition

3. 8 Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) • Counter controlled repetition – Called definite repetition • The number of loops is known before the loop starts – Uses a counter to limit the number of times a loop repeats – Counter must be incremented or decremented in the loop 2002 Prentice Hall. All rights reserved. 16

3. 8 Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) Set total to zero

3. 8 Formulating Algorithms: Case Study 1 (Counter Controlled Repetition) Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 3. 9 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem. 2002 Prentice Hall. All rights reserved. 17

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # Fig. 3. 10: fig 03_10. py # Class average program with counter-controlled repetition. The total and counter, set to # initialization phase zero and one respectively total = 0 # sum of grades grade. Counter = 1 # number of grades entered A loop the continues as long as the counter does not go past 10 # processing phase while grade. Counter <= 10: # loop 10 times grade = raw_input( "Enter grade: " ) # get one grade = int( grade ) # convert string to an integer total = total + grade Adds one to the grade. Counter = grade. Counter + 1 Fig 03_10. py counter to eventually break the loop # termination phase average = total / 10 # integer division print "Class average is", average Divides the total by the 10 to get the class average Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Program Output Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 2002 Prentice Hall. All rights reserved.

3. 9 Formulating Algorithms: Case Study 2 (Sentinel-Controlled Repetition) • Sentinel (guard) Value –

3. 9 Formulating Algorithms: Case Study 2 (Sentinel-Controlled Repetition) • Sentinel (guard) Value – A dummy value, one that the program checks for in order to break out of the loop – Sentinel values can be entered in by the user – Known as indefinite repetition • The total number of loops is unknown 2002 Prentice Hall. All rights reserved. 19

3. 9 Formulating Algorithms: Case Study 2 (Sentinel-Controlled Repetition) Initialize total to zero Initialize

3. 9 Formulating Algorithms: Case Study 2 (Sentinel-Controlled Repetition) Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Fig. 3. 12 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem. 2002 Prentice Hall. All rights reserved. 20

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 21 # Fig. 3. 13: fig 03_13. py # Class average program with sentinel-controlled repetition. # initialization phase total = 0 # sum of grades grade. Counter = 0 # number of grades entered # processing phase grade = raw_input( "Enter grade, -1 to end: " ) # get one grade = int( grade ) # convert string to an integer The – 1 acts as the dummy value, it is used to stop the program from looping while grade != -1: total = total + grade. Counter = grade. Counter + 1 grade = raw_input( "Enter grade, -1 to end: " ) grade = int( grade ) # termination phase if grade. Counter != 0: average = float( total ) / grade. Counter print "Class average is", average else: print "No grades were entered" Again a counter is used so that the program knows the total number to students Fig 03_13. py Finds the average by dividing total by the grade. Counter 2002 Prentice Hall. All rights reserved.

22 Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter

22 Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82. 5 Fig 03_13. py Program Output 2002 Prentice Hall. All rights reserved.

3. 10 Formulating Algorithms: Case Study 3 (Nested Control Structures) • Nesting – Inserting

3. 10 Formulating Algorithms: Case Study 3 (Nested Control Structures) • Nesting – Inserting one control structure into another • A loop inside of a loop • An if statement inside of a loop 2002 Prentice Hall. All rights reserved. 23

3. 10 Formulating Algorithms: Case Study 3 (Nested Control Structures) Initialize passes to zero

3. 10 Formulating Algorithms: Case Study 3 (Nested Control Structures) Initialize passes to zero Initialize failures to zero Initialize student counter to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig. 3. 14 Pseudocode for examination-results problem. 2002 Prentice Hall. All rights reserved. 24

25 Correct indentation essential! 1 2 3 4 5 6 7 8 9 10

25 Correct indentation essential! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # Fig. 3. 15: fig 03_15. py # Analysis of examination results. # initialize variables passes = 0 failures = 0 student. Counter = 1 # number of passes # number of failures # student counter Creates a loop that will break once the counter is passed 10 # process 10 students; counter-controlled loop while student. Counter <= 10: result = raw_input( "Enter result (1=pass, 2=fail): " ) result = int( result ) # one exam result if result == 1: passes = passes + 1 else: failures = failures + 1 student. Counter = student. Counter + 1 This if/else statement is nested within the while loop Fig 03_15. py Adds one to either the passes or failures counter # termination phase print "Passed", passes print "Failed", failures if passes > 8: print "Raise tuition" 2002 Prentice Hall. All rights reserved.

26 Enter result (1=pass, 2=fail): 1 Enter result (1=pass, 2=fail): 2 Enter result (1=pass,

26 Enter result (1=pass, 2=fail): 1 Enter result (1=pass, 2=fail): 2 Enter result (1=pass, 2=fail): 1 Enter result (1=pass, 2=fail): 1 Passed 9 Failed 1 Raise tuition Fig 03_15. py Program Output 2002 Prentice Hall. All rights reserved.

3. 12 Essentials of Counter-Controlled Repetition • Essentials – The counter • A named

3. 12 Essentials of Counter-Controlled Repetition • Essentials – The counter • A named variable to control the loop – Initial value • That which the counter starts at – Increment • Modifying the counter to make the loop eventually terminate – Condition • The test that the counter must pass in order to continue looping 2002 Prentice Hall. All rights reserved. 27

28 Intermezzo 1. Copy and run fig 03_13. py (see page 86). Reminder: ~chili/CSS.

28 Intermezzo 1. Copy and run fig 03_13. py (see page 86). Reminder: ~chili/CSS. E 03/Programs_from_book/ch 03/fig 03_13. py) 2. 3. 4. Format the output to look like this: Class average is 78. 130 I. e. , the average should be printed with exactly 3 digits after the comma. See figure 2. 19, page 52. Extend the program so it reads the grades of three classes numbered 1, 2 and 3; after reading all grades from one class, it should print out the average and the number of students of that class like this: Class 1 average is 59. 666 Finally the program should print out the overall average of all students (i. e. , sum of all grades divided by sum of all students). 2002 Prentice Hall. All rights reserved.

29 # Fig. 3. 13: fig 03_13. py -- REVISED solution part 1 totalgradesum

29 # Fig. 3. 13: fig 03_13. py -- REVISED solution part 1 totalgradesum = 0 totalgradecounter = 0 classcounter = 1 original program while classcounter <= 3: total = 0 # sum of grades of current class grade. Counter = 0 # number of grades entered for current class grade = raw_input( "Enter grade, -1 to end: " ) # get one grade = int( grade ) # convert string to an integer while grade != -1: total = total + grade. Counter = grade. Counter + 1 grade = raw_input( "Enter grade, -1 to end: " ) grade = int( grade ) if grade. Counter != 0: average = float( total ) / grade. Counter print "Class %d average is %. 3 f" %(classcounter, average) else: print "No grades were entered for this class" 2002 Prentice Hall. All rights reserved.

30 totalgradesum += totalgradecounter += grade. Counter classcounter += 1 if totalgradecounter != 0:

30 totalgradesum += totalgradecounter += grade. Counter classcounter += 1 if totalgradecounter != 0: average = float( totalgradesum ) / totalgradecounter print "Overall average is %. 3 f" %average else: print "No grades were entered" 2002 Prentice Hall. All rights reserved. solution part 2

31 3. 13 for Repetition Structure • The for loop – Function range is

31 3. 13 for Repetition Structure • The for loop – Function range is used to create a list of values – range ( integer ) • Values go from 0 up to given integer (i. e. , not including) – range ( integer, integer ) • Values go from first up to second integer but increases in intervals of the third integer – This loop will execute howmany times: for counter in range ( howmany ): and counter will have values 0, 1, . . howmany-1 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 0 1 2 3 4 5 6 7

1 2 3 4 5 6 0 1 2 3 4 5 6 7 8 9 32 # Fig. 3. 18: fig 03_18. py # Counter-controlled repetition with the # for structure and range function. for counter in range( 10 ): print counter Makes the counter go from zero to nine Fig 03_18. py Program Output 2002 Prentice Hall. All rights reserved.

33 range function Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44:

33 range function Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> range( 10 ) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Fig. 3. 19 Function range. Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> range( 10, 0, -1 ) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Fig. 3. 20 Function range with a third value. 2002 Prentice Hall. All rights reserved.

34 Another example 1 2 3 4 5 6 7 8 9 # Fig.

34 Another example 1 2 3 4 5 6 7 8 9 # Fig. 3. 22: fig 03_22. py # Summation with for. sum = 0 for number in range( 2, 101, 2 ): sum += number print "Sum is", sum Sum is 2550 Loops from 2 to 101 in increments of 2 A sum of all the even numbers from 2 to 100 Fig 03_22. py Program Output 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 Year 1 2

1 2 3 4 5 6 7 8 9 10 11 Year 1 2 3 4 5 6 7 8 9 10 35 # Fig. 3. 23: fig 03_23. py # Calculating compound interest. principal = 1000. 0 rate =. 05 # starting principal # interest rate print "Year %21 s" % "Amount on deposit" for year in range( 1, 11 ): amount = principal * ( 1. 0 + rate ) ** year print "%4 d%21. 2 f" % ( year, amount ) Amount on deposit 1050. 00 1102. 50 1157. 63 1215. 51 1276. 28 1340. 10 1407. 10 1477. 46 1551. 33 1628. 89 Starts the loop at 1 and goes to 10 1. 0 + rate is the same no matter what, therefore it should have been calculated outside of the loop Fig 02_23. py Program Output 2002 Prentice Hall. All rights reserved.

36 3. 15 break and continue Statements • The break statement – Used to

36 3. 15 break and continue Statements • The break statement – Used to make a loop stop looping – The loop is exited and no more loop code is executed • The continue statement – Used to continue the looping process – All following actions in the loop body are not executed • But the loop will continue to run 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 37 # Fig.

1 2 3 4 5 6 7 8 9 10 11 37 # Fig. 3. 24: fig 03_24. py # Using the break statement in a for structure. for x in range( 1, 11 ): if x == 5: break The loop will go from 1 to 10 When x equals 5 the loop breaks. Only up to 4 will be displayed print x, print "n. Broke out of loop at x =" , x 1 2 3 4 Broke out of loop at x = 5 Shows that the counter does not get to 10 like it normally would have Fig 03_24. py Program Output 2002 Prentice Hall. All rights reserved.

38 Using break to exit a loop 1 2 3 4 5 6 7

38 Using break to exit a loop 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # Fig. 3. 25: fig 03_25. py # Using the break statement to avoid repeating code # in the class-average program. # initialization phase total = 0 # sum of grades This loop of willgrades continue grade. Counter = 0 # number entered no matter what while 1: grade = raw_input( "Enter grade, -1 to end: " ) grade = int( grade ) # exit loop if user inputs -1 if grade == -1: break If total += grade. Counter += 1 the user enters – 1 then the loop ends Fig 03_25. py Keeps a count and a sum of all the grades # termination phase if grade. Counter != 0: average = float( total ) / grade. Counter print "Class average is", average else: print "No grades were entered" Finds the average by dividing total by the counter 2002 Prentice Hall. All rights reserved.

39 continue skips rest of body but continues loop 1 2 3 4 5

39 continue skips rest of body but continues loop 1 2 3 4 5 6 7 8 9 10 11 # Fig. 3. 26: fig 03_26. py # Using the continue statement in a for/in structure. for x in range( 1, 11 ): if x == 5: continue print x, The loop will continue if the value equals 5 The value 5 will never be output but all the others will Fig 03_26. py print "n. Used continue to skip printing the value 5" 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5 Program Output 2002 Prentice Hall. All rights reserved.