1 of 66Module 6 : Flow controlIntroduction to       Computational ThinkingModule 6 : Flow control #1Asst Prof Chi‐Wing FU,...
2 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts•...
3 of 66Module 6 : Flow controlBasic Concepts• The Power of Computer Programs• Program Execution• Why Selection?• Why Repet...
4 of 66Module 6 : Flow controlThe Power of Computer Programs• Help automation• Can repeat computation (which may be routin...
5 of 66Module 6 : Flow controlProgram Execution• Given a computer program, CPU runs itsinstructions one by oneThis program...
6 of 66Module 6 : Flow controlProgram Execution• But… This program only shows a basic kind ofcontrol flow, called “sequenc...
7 of 66Module 6 : Flow controlSequence alone?If I ask you to write a program for …1. Computing the average height ofstuden...
8 of 66Module 6 : Flow controlSequence alone?1) Computing the average height ofstudents in a class?• Basic idea for the al...
9 of 66Module 6 : Flow controlSequence alone?Implementation:sum = 0.0height_student = ask user inputsum += height_studenth...
10 of 66Module 6 : Flow controlSequence alone?2) A simple computer game such aspaper scissor rock?• Basic idea for the alg...
11 of 66Module 6 : Flow controlSequence alone?But… in the final step…• How can a computer program compare andtell who wins...
12 of 66Module 6 : Flow controlSo… we need• Selection – A computer program candynamically choose which instruction(s) to b...
13 of 66Module 6 : Flow controlSo… we need• Looping – A computer program candynamically choose how many times itrepeats ce...
14 of 66Module 6 : Flow controlComputational thinking - Looping1) To compute the average height of thestudents in a class•...
15 of 66Module 6 : Flow controlComputational thinking - Selection2) Game: paper scissor rock• A program can compare choice...
16 of 66Module 6 : Flow controlWhat is Flow Control / Control Flow?• It is to control which instruction to beexecuted next...
17 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts...
18 of 66Module 6 : Flow controlBasic Concept: IF• Form #1: IF statementIF condition is TrueTHENDO THISEND IF……Hence… Progr...
19 of 66Module 6 : Flow controlBasic Concept: IF• Form #1: IF statementIF condition is TrueTHENDO THISEND IF……Adopted in m...
20 of 66Module 6 : Flow controlExamples• Example #1IF body temperature > 37.5THENprint("Fever!")print("Time to see doctor!...
21 of 66Module 6 : Flow controlBasic Concept: IF-ELSE• Form #2: IF-ELSEIF condition is TrueTHENSUITE1ELSESUITE2END IF……Exe...
22 of 66Module 6 : Flow controlExamples• Example #2.1IF body temperature > 37.5 THENprint("Fever! See doctor")END IFIF bod...
23 of 66Module 6 : Flow controlExamples• Example #2.2IF body temperature > 37.5THENprint("Fever! See doctor")ELSEprint("No...
24 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-ELSEIF condition1 is True THENDO SUITE AELIF ...
25 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-ELSEIF condition1 is True THENDO SUITE AELIF ...
26 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-…-ELSE statementIF condition1 is True THENDO ...
27 of 66Module 6 : Flow controlExamples• Example #3Let’s write a simple number guessing game.The computer program randomly...
28 of 66Module 6 : Flow controlExamples• Example #3.1……IF my_guess > computer_num THENprint("Your guess is too large")END ...
29 of 66Module 6 : Flow controlExamples• Example #3.2……IF my_guess > computer_num THENprint("Your guess is too large")ELIF...
30 of 66Module 6 : Flow controlExamples• Example #3.3IF my_guess > computer_num THENprint("Your guess is too large")ELIF m...
31 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Recall that for each IF statement, ...
32 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Inside this True block (even the Fa...
33 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• And… inside the TRUE block of the T...
34 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Or even with ELSE inside…IF conditi...
35 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Or use it on the False side…IF cond...
36 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts...
37 of 66Module 6 : Flow controlCase Study: paper scissor rock• Recall our paper scissor rock game• Assume:Variable comp_ch...
38 of 66Module 6 : Flow controlCase Study: paper scissor rock• Let’s analyze the problem…• Without using IF-ELSE and neste...
39 of 66Module 6 : Flow control1st attempt• So… Pseudo code #4.1IF comp_choice == paper and your_choice == paper THENprint...
40 of 66Module 6 : Flow control1st attempt• So… Pseudo code #4.1IF comp_choice == paper and your_choice == paper THENprint...
41 of 66Module 6 : Flow control2nd attempt• Pseudo code #4.2IF comp_choice == paper THENIF your_choice == paper THENprint(...
42 of 66Module 6 : Flow control3rd attempt• Pseudo code #4.3IF comp_choice == paper THENIF your_choice == paper THENprint(...
43 of 66Module 6 : Flow control4th attempt• Pseudo code #4.4IF comp_choice == paper THENIF your_choice == paper THENprint(...
44 of 66Module 6 : Flow controlAnother approach - 5th attempt• Pseudo code #4.5IF ( comp_choice == paper and your_choice =...
45 of 66Module 6 : Flow controlAnother approach - 6th attempt• Pseudo code #4.6… Even betterIF comp_choice == your_choice ...
46 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts...
47 of 66Module 6 : Flow controlPython SyntaxNow… let’s look at how Python implements• IF statement• IF-ELSE statement• IF-...
48 of 66Module 6 : Flow controlSyntax #1• IF statement in PythonSyntax:if <a boolean expression> :one or more indented sta...
49 of 66Module 6 : Flow controlSyntax #1 cont.Note:1) Colon : marks thebeginning of a block!2) In Python, indentation -- n...
50 of 66Module 6 : Flow controlSyntax #2• IF-ELSE statementif a > b:print("a > b")else:print("a <= b")In Python, alwaysRem...
51 of 66Module 6 : Flow controlSyntax #3• IF-ELIF-ELSE statementif a > b:print("a > b")print("case 1 here")elif a < b:prin...
52 of 66Module 6 : Flow controlNested IF – No new syntax• Comparing a, b, and c:if a >= b:if a >= c:print("maximum value i...
53 of 66Module 6 : Flow controlBugs fixed• Nested IFif a >= b:if a >= c:print("maximum value is ",a)else:print("maximum va...
54 of 66Module 6 : Flow controlSyntax #4• In Python• 0, ‘’, [ ] or other “empty” objects are equivalentto False; anything ...
55 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts...
56 of 66Module 6 : Flow controlPython Implementation• Now… Let’s revisit the examples we wentthrough in real Python code• ...
57 of 66Module 6 : Flow controlExamples Revisit in Python• Example #1- Compare with the pseudo codewe saw previously- Pyth...
58 of 66Module 6 : Flow controlExamples Revisit in Python• Example #2.2- Remember to put colon also for else!(it marks the...
59 of 66Module 6 : Flow controlExamples Revisit in Python• Example #3.3Use this print()temporarily forcode testingwhen the...
60 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.1Very tedious
61 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.4Code Simplified
62 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.6By analyzing the pattern, we canfurther simplify th...
63 of 66Module 6 : Flow controlExercises!Trace these code carefully and understand its control flow.Can you draw the flow ...
64 of 66Module 6 : Flow controlMore Exercises!
65 of 66Module 6 : Flow controlTake Home Messages• Computational thinking or algorithm design requires thecareful and thou...
66 of 66Module 6 : Flow controlReading Assignment• TextbookChapter 2: Control2.1 to 2.4Note: Though some material (2.3 and...
Upcoming SlideShare
Loading in …5
×

Lecture 6.1 flow control selection

745 views

Published on

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
745
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
8
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Lecture 6.1 flow control selection

  1. 1. 1 of 66Module 6 : Flow controlIntroduction to       Computational ThinkingModule 6 : Flow control #1Asst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104email: cwfu[at]ntu.edu.sg
  2. 2. 2 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts• Case study: Paper Scissor Rock• Syntax• Examples in Python• Repetition (Looping)• Basic concepts: for and while• Syntax: while• The range function• Syntax: for• Nested loops• break, continue, and pass• Case Study: Visual Example - Path of a projectile
  3. 3. 3 of 66Module 6 : Flow controlBasic Concepts• The Power of Computer Programs• Program Execution• Why Selection?• Why Repetition?• What is Flow Control / Control Flow?
  4. 4. 4 of 66Module 6 : Flow controlThe Power of Computer Programs• Help automation• Can repeat computation (which may be routinejob) with high reliability and reusability• Reliability – low error rate (compared to human)• Reusability – same piece of code run again and again• Can be embedded to enhance many daily lifedevices: phone, TV, fridge, cooker, etc.• How many computers you now have?
  5. 5. 5 of 66Module 6 : Flow controlProgram Execution• Given a computer program, CPU runs itsinstructions one by oneThis program can automate the computation of circle areaand circumference; no matter how many times we run it,it can reliably do the same computation consistently
  6. 6. 6 of 66Module 6 : Flow controlProgram Execution• But… This program only shows a basic kind ofcontrol flow, called “sequence”• If we only have “sequence” in programming…Is it enough? What cannot be done?Step 1 Step 2 Step 3 ……
  7. 7. 7 of 66Module 6 : Flow controlSequence alone?If I ask you to write a program for …1. Computing the average height ofstudents in a class?2. A simple computer game such aspaper scissor rock?
  8. 8. 8 of 66Module 6 : Flow controlSequence alone?1) Computing the average height ofstudents in a class?• Basic idea for the algorithm:Sum all height values and Divide it by total• If we only have sequence…We need to repeat certain instruction, e.g.,accumulate height of students, exactly N times,where N is the total number of students
  9. 9. 9 of 66Module 6 : Flow controlSequence alone?Implementation:sum = 0.0height_student = ask user inputsum += height_studentheight_student = ask user inputsum += height_student...average = sum / NBut…• Different classes have different number of students!!!• So, the program is not reusable and has to bechanged for different classes and years. Tedious!Need torepeat thisN times
  10. 10. 10 of 66Module 6 : Flow controlSequence alone?2) A simple computer game such aspaper scissor rock?• Basic idea for the algorithm here:1. First, the computer program has torandomize a choice out of the three2. Then get user input (user’s choice)3. Finally, the computer programcompares the two choices anddetermines who wins
  11. 11. 11 of 66Module 6 : Flow controlSequence alone?But… in the final step…• How can a computer program compare andtell who wins?• With “sequence” …Every step is pre-plannedand fixed; there is ONLY one possibleconsequence (control flow) in the program• But… sometimeshuman wins; sometimescomputer wins...
  12. 12. 12 of 66Module 6 : Flow controlSo… we need• Selection – A computer program candynamically choose which instruction(s) to beexecuted next based on certain condition(s)during the program runtime• Different instructions can be selected to run atdifferent time• BUT the program is the same (we do not need tochange and compile it again for different situations;we already define possible program responses fordifferent cases when writing the program)
  13. 13. 13 of 66Module 6 : Flow controlSo… we need• Looping – A computer program candynamically choose how many times itrepeats certain instruction(s) during theprogram runtime• Program instructions can be repeated dynamically;sometimes 3 times, sometimes 1000 times, orsometimes even 0 times• Again, the program is the same (we do not need tochange it for different number of repetitions)
  14. 14. 14 of 66Module 6 : Flow controlComputational thinking - Looping1) To compute the average height of thestudents in a class• We may repeat the height accumulationbased on the value of Nsum = 0.0REPEAT N timesASK user for next student’s heightsum += heightEND of REPEATaverage = sum / NSame program can workno matter how manystudents; more reusable
  15. 15. 15 of 66Module 6 : Flow controlComputational thinking - Selection2) Game: paper scissor rock• A program can compare choices from human andcomputer, and then determine who winsIF user_choice == paperand computer_choice == scissorprint("computer wins")IF user_choice == scissorand computer_choice == paperprint("human wins")... # for other cases
  16. 16. 16 of 66Module 6 : Flow controlWhat is Flow Control / Control Flow?• It is to control which instruction to beexecuted next• By default, it is defined by the “sequence”concept, i.e., one after the other• But selection and repetition can alter the flow…When you write/read a program,make sure you understand the flow!!!i.e., what is to be executed next for every step…The flow control in a program -> Its Logic!!!
  17. 17. 17 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts• Case study: Paper Scissor Rock• Syntax• Examples in Python• Repetition (Looping)• Basic concepts: for and while• Syntax: while• The range function• Syntax: for• Nested loops• break, continue, and pass• Case Study: Visual Example - Path of a projectile
  18. 18. 18 of 66Module 6 : Flow controlBasic Concept: IF• Form #1: IF statementIF condition is TrueTHENDO THISEND IF……Hence… Program can make decisions!!!Whether toexecute it or not depends on thecondition during program runtimeAfter that, continue the sequenceand execute the next instructionan IF statement
  19. 19. 19 of 66Module 6 : Flow controlBasic Concept: IF• Form #1: IF statementIF condition is TrueTHENDO THISEND IF……Adopted in many programming languages withproper indentation! Python forces you!!!We usually indent thesestatement(s) to improve thecode readability that this partbecomes to the true condition
  20. 20. 20 of 66Module 6 : Flow controlExamples• Example #1IF body temperature > 37.5THENprint("Fever!")print("Time to see doctor!")END IF……The power of IF statement is that theprogram can selectively run the blockbased on the runtime condition!!!Sometimes run it! Sometimes skip it!In Python, this groupof indented statement(s)is called a suite/block.(compound statement:a set of statementsbeing used as a group)
  21. 21. 21 of 66Module 6 : Flow controlBasic Concept: IF-ELSE• Form #2: IF-ELSEIF condition is TrueTHENSUITE1ELSESUITE2END IF……Execute true partif condition is trueAfter that, continue the sequenceand execute the next instructionExecute false partif condition is false (also indented)A (single) IF-ELSE statement in the top level
  22. 22. 22 of 66Module 6 : Flow controlExamples• Example #2.1IF body temperature > 37.5 THENprint("Fever! See doctor")END IFIF body temperature <= 37.5 THENprint("Normal!")END IF…… Here we use two consecutiveIF statements for true and false sidesAny issue? Efficiency? Redundancy?
  23. 23. 23 of 66Module 6 : Flow controlExamples• Example #2.2IF body temperature > 37.5THENprint("Fever! See doctor")ELSEprint("Normal!")END IF……The power of IF-ELSEstatement is that the programbecomes more efficient!JUST ONE checking(temperature > 37.5) can let usknow which way to go!!Avoid redundant check!
  24. 24. 24 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-ELSEIF condition1 is True THENDO SUITE AELIF condition2 is True THENDO SUITE BELSEDO SUITE CEND IF……Execute A if condition 1 is truethen skip B and CNo matter after which case, wecontinue here (sequence concept)Execute B if condition 1 is falseand condition 2 is true, then skip CExecute C if both conditions1 and 2 are falseElse ifThe whole statement
  25. 25. 25 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-ELSEIF condition1 is True THENDO SUITE AELIF condition2 is True THENDO SUITE BELSEDO SUITE CEND IF……
  26. 26. 26 of 66Module 6 : Flow controlBasic Concept: IF-ELIF-ELSE• Form #3: IF-ELIF-…-ELSE statementIF condition1 is True THENDO SUITE AELIF condition2 is True THENDO SUITE BELIF condition3 is True THENDO SUITE CELSEDO SUITE D # conditions 1,2,3 are all falseEND IF……You may havemany … manyELIF blocksThe whole statement
  27. 27. 27 of 66Module 6 : Flow controlExamples• Example #3Let’s write a simple number guessing game.The computer program randomly pick anumber in-between 0 and 50 (inclusively).You can make a guess and the computercan tell you whether your guess is the same,too large, or too small.
  28. 28. 28 of 66Module 6 : Flow controlExamples• Example #3.1……IF my_guess > computer_num THENprint("Your guess is too large")END IFIF my_guess < computer_num THENprint("Your guess is too small")END IFIF my_guess == computer_num THENprint("Bingo!!! Correct")END IF…… 1) Is this program logically correct?2) Efficient? Any redundant check?Three consecutiveIF statements
  29. 29. 29 of 66Module 6 : Flow controlExamples• Example #3.2……IF my_guess > computer_num THENprint("Your guess is too large")ELIF my_guess < computer_num THENprint("Your guess is too small")ELIF my_guess == computer_num THENprint("Bingo!!! Correct")END IF……1. Is it better?If condition 1 is true,no need to checkothers (they must be F)2. But can you makeit even better?
  30. 30. 30 of 66Module 6 : Flow controlExamples• Example #3.3IF my_guess > computer_num THENprint("Your guess is too large")ELIF my_guess < computer_num THENprint("Your guess is too small")ELSEprint("Bingo!!! Correct")END IF……When comparing twonumbers, there areonly three possibilities!!!If it is not the first twocases, must be thethird case!!!
  31. 31. 31 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Recall that for each IF statement, there is anassociated block for its TRUE partIF condition1 is True THENDO THIS SUITEEND IF……
  32. 32. 32 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Inside this True block (even the False block),you may have another IF statement(s)IF condition1 is True THENIF condition2 is True THENDO THIS SUITEENDIFEND IF……This is callednested IF* Note the properindentation
  33. 33. 33 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• And… inside the TRUE block of the TRUEblock, you may still use IF statement(s)IF condition1 is True THENIF condition2 is True THENIF condition3 is True THENDO THISENDIFENDIFEND IFWe DO THIS only ifcondition 1 is true,condition 2 is true,and condition 3 is trueSIMILAR to AND’ed
  34. 34. 34 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Or even with ELSE inside…IF condition1 is True THENIF condition2 is True THENDO SUITE AELSEDO SUITE BEND IFEND IF
  35. 35. 35 of 66Module 6 : Flow controlBasic Concept: Nested IF• Form #4: Nested IF statement• Or use it on the False side…IF condition1 is True THENDO SUITE AELSEIF condition2 is True THENDO SUITE BELSEDO SUITE CEND IFEND IFWhich one to use?It’s all about the logicfor problem solving
  36. 36. 36 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts• Case study: Paper Scissor Rock• Syntax• Examples in Python• Repetition (Looping)• Basic concepts: for and while• Syntax: while• The range function• Syntax: for• Nested loops• break, continue, and pass• Case Study: Visual Example - Path of a projectile
  37. 37. 37 of 66Module 6 : Flow controlCase Study: paper scissor rock• Recall our paper scissor rock game• Assume:Variable comp_choice stores computer’schoice on paper, scissor, or rock, whileVariable your_choice stores your choice
  38. 38. 38 of 66Module 6 : Flow controlCase Study: paper scissor rock• Let’s analyze the problem…• Without using IF-ELSE and nested-IF, if weonly use IF statements, how many possiblecombinations of choices?There are3 x 3 possiblecombinations
  39. 39. 39 of 66Module 6 : Flow control1st attempt• So… Pseudo code #4.1IF comp_choice == paper and your_choice == paper THENprint("draw")END IFIF comp_choice == paper and your_choice == rock THENprint("computer wins")END IFIF comp_choice == paper and your_choice == scissor THENprint("you win")END IF…… # just continue with the# remaining six cases ….Is it logically correct?Good program?Efficient?We exhaust all possiblecombinations of input
  40. 40. 40 of 66Module 6 : Flow control1st attempt• So… Pseudo code #4.1IF comp_choice == paper and your_choice == paper THENprint("draw")END IFIF comp_choice == paper and your_choice == rock THENprint("computer wins")END IFIF comp_choice == paper and your_choice == scissor THENprint("you win")END IF……Notice anything in common?… the first three IF statements?Do we check them redundantly
  41. 41. 41 of 66Module 6 : Flow control2nd attempt• Pseudo code #4.2IF comp_choice == paper THENIF your_choice == paper THENprint("draw")END IFIF your_choice == rock THENprint("computer wins")END IFIF your_choice == scissor THENprint("you win")END IFEND IF……We can combine them byusing nested IF… then, canavoid redundant comparison!!!Exercise: Draw the flowchart
  42. 42. 42 of 66Module 6 : Flow control3rd attempt• Pseudo code #4.3IF comp_choice == paper THENIF your_choice == paper THENprint("draw")ELIF your_choice == rock THENprint("computer wins")ELIF your_choice == scissor THENprint("you win")END IFEND IF……Further use ELIF (else if) toavoid redundant checks!What check(s) may be avoided?Exercise: Draw the flowchart
  43. 43. 43 of 66Module 6 : Flow control4th attempt• Pseudo code #4.4IF comp_choice == paper THENIF your_choice == paper THENprint("draw")ELIF your_choice == rock THENprint("computer wins")ELSEprint("you win")END IFEND IF……Further use ELSE to avoidone more redundant check!Exercise: Draw the flowchart(it slightly differs from previous two)
  44. 44. 44 of 66Module 6 : Flow controlAnother approach - 5th attempt• Pseudo code #4.5IF ( comp_choice == paper and your_choice == paper )or ( comp_choice == rock and your_choice == rock )or ( comp_choice == scissor and your_choice == scissor ) THENprint("draw")ELIF ( comp_choice == paper and your_choice == rock )or ( comp_choice == rock and your_choice == scissor )or ( comp_choice == scissor and your_choice == paper ) THENprint("computer wins")ELSEprint("you win")END IF We may have many other solutions!Different ways of computational thinking!Think: based onpossible outcomes
  45. 45. 45 of 66Module 6 : Flow controlAnother approach - 6th attempt• Pseudo code #4.6… Even betterIF comp_choice == your_choice THENprint("draw")ELIF ( comp_choice == paper and your_choice == rock )or ( comp_choice == rock and your_choice == scissor )or ( comp_choice == scissor and your_choice == paper ) THENprint("computer wins")ELSEprint("you win")END IF Hope that you enjoy computationalthinking and programming…(note: we are not using Python yet)Further simplified
  46. 46. 46 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts• Case study: Paper Scissor Rock• Syntax• Examples in Python• Repetition (Looping)• Basic concepts: for and while• Syntax: while• The range function• Syntax: for• Nested loops• break, continue, and pass• Case Study: Visual Example - Path of a projectile
  47. 47. 47 of 66Module 6 : Flow controlPython SyntaxNow… let’s look at how Python implements• IF statement• IF-ELSE statement• IF-ELIF-ELSE statement• Nested IF
  48. 48. 48 of 66Module 6 : Flow controlSyntax #1• IF statement in PythonSyntax:if <a boolean expression> :one or more indented statementsExample:if a > b:print( "a > b" )MUST usecolon hereMUST useindentation for theentire true block
  49. 49. 49 of 66Module 6 : Flow controlSyntax #1 cont.Note:1) Colon : marks thebeginning of a block!2) In Python, indentation -- not just for readabilitybut also for defining the scope of a block!3) Number of whitespaces for indentation isflexible but should be consistent for the samelevel in the same programMore keywords in Python• else (see syntax #2)• elif (see syntax #3)
  50. 50. 50 of 66Module 6 : Flow controlSyntax #2• IF-ELSE statementif a > b:print("a > b")else:print("a <= b")In Python, alwaysRemember that colonmarks the beginningof a block/suite*** Don’t forget it!!!else syntax error
  51. 51. 51 of 66Module 6 : Flow controlSyntax #3• IF-ELIF-ELSE statementif a > b:print("a > b")print("case 1 here")elif a < b:print("a < b")print("case 2 here")else:print("a == b")print("case 3 here")In Python, indentationdefines a block!!!So if you continue touse the same amountof indentation, it isstill in the same block
  52. 52. 52 of 66Module 6 : Flow controlNested IF – No new syntax• Comparing a, b, and c:if a >= b:if a >= c:print("maximum value is ",a)elseprint("maximum value is ",c)elseif b >= c:print("maximum value is ",b)elseprint("maximum value is ",c)endAny bug(s)here?(no logic error)
  53. 53. 53 of 66Module 6 : Flow controlBugs fixed• Nested IFif a >= b:if a >= c:print("maximum value is ",a)else:print("maximum value is ",c)else:if b >= c:print("maximum value is ",b)else:print("maximum value is ",c)six syntaxerrors fixed!needproperindentation
  54. 54. 54 of 66Module 6 : Flow controlSyntax #4• In Python• 0, ‘’, [ ] or other “empty” objects are equivalentto False; anything else is equivalent to TrueRun itMore info: http://docs.python.org/library/stdtypes.html#truth-value-testing
  55. 55. 55 of 66Module 6 : Flow controlTopics• Basic Concepts: Why Selection and Repetition• Selection (Branching)• Basic concepts• Case study: Paper Scissor Rock• Syntax• Examples in Python• Repetition (Looping)• Basic concepts: for and while• Syntax: while• The range function• Syntax: for• Nested loops• break, continue, and pass• Case Study: Visual Example - Path of a projectile
  56. 56. 56 of 66Module 6 : Flow controlPython Implementation• Now… Let’s revisit the examples we wentthrough in real Python code• See the beauty and simplicity of Python
  57. 57. 57 of 66Module 6 : Flow controlExamples Revisit in Python• Example #1- Compare with the pseudo codewe saw previously- Python code is simple and clear
  58. 58. 58 of 66Module 6 : Flow controlExamples Revisit in Python• Example #2.2- Remember to put colon also for else!(it marks the beginning of a block)
  59. 59. 59 of 66Module 6 : Flow controlExamples Revisit in Python• Example #3.3Use this print()temporarily forcode testingwhen there is arandom scenario;When done,just comment itNote:
  60. 60. 60 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.1Very tedious
  61. 61. 61 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.4Code Simplified
  62. 62. 62 of 66Module 6 : Flow controlExamples Revisit in Python• Example #4.6By analyzing the pattern, we canfurther simplify the codestatementcontinuity
  63. 63. 63 of 66Module 6 : Flow controlExercises!Trace these code carefully and understand its control flow.Can you draw the flow charts for these code?What is/are the conditions for reaching each print()?Note: condition_A, condition_B, etc., are boolean variables
  64. 64. 64 of 66Module 6 : Flow controlMore Exercises!
  65. 65. 65 of 66Module 6 : Flow controlTake Home Messages• Computational thinking or algorithm design requires thecareful and thoughtful applications of sequence, selection(branching) and repetition (looping) to control the flow• #1 Understand: be able to trace code and understand thecontrol flow inside a given program• #2 Analysis: Given a problem, think and analyze carefullydifferent possibilities/combinations and the logic• #3 Apply: Furthermore, transform the logic appropriatelyinto IF-ELSE, IF-ELIF-ELSE and nested IF• #4 Test: Lastly, use sufficient test data to evaluate yourprogram with different consequencesLast word… practice practice practice
  66. 66. 66 of 66Module 6 : Flow controlReading Assignment• TextbookChapter 2: Control2.1 to 2.4Note: Though some material (2.3 and 2.4) intextbook is not directly related to the lecturematerial, you can learn more from them.

×