Lecture 6.2  flow control repetition
Upcoming SlideShare
Loading in...5
×
 

Lecture 6.2 flow control repetition

on

  • 223 views

 

Statistics

Views

Total Views
223
Views on SlideShare
223
Embed Views
0

Actions

Likes
1
Downloads
7
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Lecture 6.2  flow control repetition Lecture 6.2 flow control repetition Presentation Transcript

    • 1 of 81Module 6 : Flow controlIntroduction to       Computational ThinkingModule 6 : Flow control #2Asst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104email: cwfu[at]ntu.edu.sg
    • 2 of 81Module 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 of 81Module 6 : Flow controlBasic Concepts• Recall the motivation example to computeaverage student height in a class
    • 4 of 81Module 6 : Flow controlBasic Concepts• With the looping mechanism, we canrepeat certain code arbitrarily numberof times based on the need
    • 5 of 81Module 6 : Flow controlGeneral structure of a loopGenerally, four steps:1. Initialize: loop control variable2. Test: continue the loop or not?3. Loop body: main computation being repeated4. Update: modify the value of loop control variable sothat next time when we test, we MAY exit the loopSometimes a loop may not have all of them,e.g., infinite loop (test is always true)
    • 6 of 81Module 6 : Flow controlGeneral structure of a loopVisualize them by a flow chart!!!1. Initialize2. Test3. Loop body4. UpdateInitializeStatementUpdateTesttruefalse4321Loop
    • 7 of 81Module 6 : Flow controlmain:SET sum TO 0 // InitializeSET counter TO 0WHILE counter < N // TestREAD height // Loop bodyADD height TO sumINCREMENT counter BY 1 // UpdateENDWHILECOMPUTE average = sum/counterPRINT averageGeneral structure of a loopExample: Compute average height of N students1234
    • 8 of 81Module 6 : Flow controlTwo kinds of loop1. Counter-controlled loop – the number ofrepetitions is known before the loop startsexecution; just repeat the loop on eachelement in a preset sequence2. Sentinel-controlled loop – the number ofrepetitions is NOT known before the loopstarts. For example, a sentinel value (e.g., –1,different from the regular data) is used todetermine whether to execute the loop body
    • 9 of 81Module 6 : Flow controlExamples:• Counter-controlled loopsCompute average student height in a class…Assumption: we know the number of studentsbefore we start the loop
    • 10 of 81Module 6 : Flow controlExamples:• Sentinel-controlled loopsCompute average height of people enteringCanteen A in a day…sum = count = 0time = get current timeWHILE time < Canteen A closing timeheight = get height of next guysum += heightcount += 1time = get current timeEND WHILECannot know ahead how many people enteringcanteen A before we start the loop body
    • 11 of 81Module 6 : Flow controlExamples:• A Sentinel-controlled loopusually contains all four loop elementsInitializeTestLoop BodyUpdateNote: time is the loop control variable
    • 12 of 81Module 6 : Flow controlIn PythonWe can implement loops by:• for – usually for counter-controlled loops• while – usually for sentinel-controlledloop, but may also be used to implementcounter-controlled loops
    • 13 of 81Module 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
    • 14 of 81Module 6 : Flow controlPython Syntax: while• Similar to an IF statement but repeat theblock till the condition becomes falseSyntax:while <boolean expression> :suite (one or moreindented statements)Example:while a > b:print(a," > ",b)a = a - 10MUST use colon followedby proper indentationthe wholewhile structureTesttrueStatementfalse
    • 15 of 81Module 6 : Flow controlAny difference? Try them!!!Order is importantThe control FLOW!!!Indentation is importantIt defines a block
    • 16 of 81Module 6 : Flow controlExample #1.1• Compute and print a conversion table betweenFahrenheit and Celsius, starting from 0 deg. C
    • 17 of 81Module 6 : Flow controlPrint messageRead tempLimitStartfahren = 32.0fahren<=tempLimit ?truefahren += 10Print fahren, celsiusfalseEndInitializewhile (Test)StatementUpdateLoop BodyTestcelsius = (fahren– 32.0) * 5.0 / 9.0
    • 18 of 81Module 6 : Flow controlImplementation• Who is the loop control variable?• Counter-controlled or sentinel-controlled?Note: You will learn how to format the output as below forprint() by using % in module 8 on Stringst - a tab space (nicer formatting)
    • 19 of 81Module 6 : Flow controlCheck loop iteration: tableFalse122.044.4True112.0………5.6True42.00True32.0Output Celsiusfahren < tempLimitfahren
    • 20 of 81Module 6 : Flow controlAny issue?• Any potential issue in this program?How if the user enters a value smaller than 32? Or? Then?What will happen? So… Any idea to fix it?
    • 21 of 81Module 6 : Flow controlExample #1.2• Maybe… we can force the user to inputagain? But how?• Idea:• Keep asking until he/she enters a number that isat least 32 and at most a certain reasonable limit• Now… we can add a while loop
    • 22 of 81Module 6 : Flow controlImplementationNew whileIn the new loop:• Who is the loop control variable?• Counter-controlled or sentinel-controlled?( ) is ok butredundant
    • 23 of 81Module 6 : Flow controlNote:• while loop is useful if we want torepeatedly ask user for input until theinput fulfills our requirement
    • 24 of 81Module 6 : Flow controlExample #1.3• Write a program to read numbers fromuser; sum them up until the input is -1(sentinel value)Indicate an end
    • 25 of 81Module 6 : Flow controlImplementation• Again, we can use while loop tocontinue asking for user input…• Who is the loop control variable?• Counter-controlled or sentinel-controlled?• Any issue to ensure for this design?[Make sure: sentinel value will not appear in normal cases]whilestructure
    • 26 of 81Module 6 : Flow controlPython Syntax: while with else• while loop, oddly, can have an associatedelse statement• else statement is executed when the loopfinishes under normal conditions• The last thing the loop does as it exits• Syntax:while booleanExpression:suite1else:suite2rest of the programthe wholewhilestructure
    • 27 of 81Module 6 : Flow controlPython Syntax: while with else
    • 28 of 81Module 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
    • 29 of 81Module 6 : Flow controlrange• Before we discuss "for" loop, we firstlearn a useful built-in function in Pythoncalled range()• Note: range() is often used in "for" loop
    • 30 of 81Module 6 : Flow controlWhat is range?• Generates a list of integers from start up toend (but excluding end) with stepsize step• Syntax: it has three forms:range( end )range( start , end )range( start , end , step )i.e., we can use/call it in three different ways…
    • 31 of 81Module 6 : Flow controlMeaning• range( end )- Python puts start to 0 and step to 1 (default values)- range(11) gives [ 0 , 1 , 2 , … , 10 ]• range( start , end )- Python puts step to 1 (default value)- range(1,11) gives [ 1 , 2 , 3 , … , 10 ]• range( start , end , step )- Python returns a list (sequence) of integers fromstart to end-1 with stepsize step- range(1,11,2) gives [ 1 , 3 , 5 , …, 9 ]However, range() returns a memory efficient object implicitly ratherthan an explicit list; we can use list to see its contents, see next page
    • 32 of 81Module 6 : Flow controlcount downInfinite! returns an empty list (“list” is aError! Only integers!start from 0 and step 1sequence)returns a memory efficient object
    • 33 of 81Module 6 : Flow controlExercises for you• How can you create a list containing[ 0, 3, 6, 9, 12, 15 ] ?• How can you create a list containing[ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] ?• How can you create a list containing[ 4, 2, 0, -2, -4 ] ?
    • 34 of 81Module 6 : Flow controlWhat is memory efficient object?• range() returns a “range object” (memoryefficient object) that pretends to be the sequence• It is an opaque sequence which yields the samevalues as "list(range())”,but NOT storing everysingle value explicitly; it generates values for youonly when you use its contents (on demand)• Any advantage? Think about…Try range(1,1000000)and list(range(1,1000000))Which one consumes more memory?
    • 35 of 81Module 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
    • 36 of 81Module 6 : Flow controlPython Syntax: for• Control flow: loop through the objectsaccording to their order in the sequenceSyntax:for <element> in <sequence> :suite (one or more indented statements)Example:for each element in ittwo forstructurescan be a list also…
    • 37 of 81Module 6 : Flow controlNote:Main issue:• Variable x (or y) in the example “for” loops will takedifferent values in different loop iterationsOther issues:• First, remember the colon!!!• Second, why it is always counter-controlled?• Lastly, remember range in Python!!Excluding the ending elementi.e., not symmetric!!!range(1,5,1) != range(5,1,-1)
    • 38 of 81Module 6 : Flow controlExample #2.1• Problem: print a multiplication table of a certainnumber, e.g., 9, see below:
    • 39 of 81Module 6 : Flow controlExample #2.1 – Algorithm?• First, ask user for a number• Then, loop from 1 to 10, compute themultiplication, and display the formulae
    • 40 of 81Module 6 : Flow controlExample #2.1 – Implementation• In Python, just a few lines…Use comma to separatedifferent elements for printEnd with 11 insteadof 10 if we want thelast value to be 10
    • 41 of 81Module 6 : Flow controlCase Study: Example #2.2• Summing a series of data using for loop!10x!4x!3x!2x1!x110432+−+−+− LLBasic idea to implement it:Sum the terms one by one by using a for loop,i.e., one term per iteration
    • 42 of 81Module 6 : Flow controlCase Study: Example #2.2• Let’s analyze the termObservation:• First, check the terms…• 1st term is 1; 2nd term is• Multiply 1st term with x, divide by 1 and flip the sign• Third term is• Multiply 2nd term with x, divide by 2 and flip the sign……!10x!4x!3x!2x1!x110432+−+−+− LL
    • 43 of 81Module 6 : Flow controlCase Study: Example #2.2• More detailed idea to implement itSo...• We may have one variable to keep track of the term,say term• One more variable to keep track of what to bedivided next, say divisor• Another variable to accumulate the sum, say total!10x!4x!3x!2x1!x110432+−+−+− LL
    • 44 of 81Module 6 : Flow controlCase Study: Example #2.2• Hence, we have:Note:- Make sure use float forx and term- The negative sign beforeterm can flip the sign ofthe term in each iteration- I put in this “print(term)”for testing purpose;note: testing is importantto verify your code!!!(after that, can justcomment it)
    • 45 of 81Module 6 : Flow controlInputs/initialization:x = 0.9, total= 1.0, term = 1.0Case Study: Example #2.2• We can trace each iteration to verify also:Outputs:Result = 0.406569…+1-1sign0.4065699.609e-0810…0.5050.40520.0999-0.91totaltermdivisor… …
    • 46 of 81Module 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 of 81Module 6 : Flow controlNested Loops• Sometimes… one level of loop is not sufficientfor the algorithmic need; an outer loop mayenclose an inner loop (or even more), e.g.,Two levels of loops!!!
    • 48 of 81Module 6 : Flow controlExample #2.3• Note:This additional argument is used inPython 3 to avoid the default ending nThis is the entiresuite/block insidethe outer for loopOnly one statementinside the inner for loopQuestion:How many times each print is executed?What is the control flow?
    • 49 of 81Module 6 : Flow controlCase study: Example #2.4• Printing the full Multiplication TablePrint out fromthe program:How many times eachof these print statementsis executed?
    • 50 of 81Module 6 : Flow controlCase study: Example #2.5• Print a pattern, e.g., triangular pattern:First… observe andanalyze the pattern…How many stars on each level?How many leading white spaces?
    • 51 of 81Module 6 : Flow controlCase study: Example #2.5• Implementation
    • 52 of 81Module 6 : Flow controlCase study: Example #2.5.1• Use while loops inside insteadHow many times these print functions are called?Changetowhile
    • 53 of 81Module 6 : Flow controlMore Patterns?• Can you write programsto print out each of thesepatterns?
    • 54 of 81Module 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
    • 55 of 81Module 6 : Flow controlWhat are break and continue?• Python keywords that can alter control flowin a loop• Let’s start with the following simple loop:- What will be printed if werun this program?- How many times the loopis iterated?- Note the else: statementfor while
    • 56 of 81Module 6 : Flow controlWhat are break and continue?• Print out of running this program
    • 57 of 81Module 6 : Flow controlbreak• Meaning: Executing break exits the immediateloop that contains itCompared to prev. page:We add if and breakControl flow knowledge:Go after the wholeenclosing loop
    • 58 of 81Module 6 : Flow controlbreak• And break is considered as an abnormal exitfrom the loop… so?No morehere3!
    • 59 of 81Module 6 : Flow controlbreak• How if we include everything in a for loop?This time, we add the outer forBasically a for statementThe print-out doubled!!Note: break affects only theinner loop that contains it
    • 60 of 81Module 6 : Flow controlcontinue• To understand continue…Let’s go back to the basic example:
    • 61 of 81Module 6 : Flow controlcontinue• Skips the rest of the loop body and goes back tothe test in the loop that contains itCompare to prev. page:We add if and continueControl flow knowledge:Go immediately to testin the enclosing loop
    • 62 of 81Module 6 : Flow controlcontinue• If we run the program, print “here2” will onlybe reached two times… why?For continue, make sureloop control variable can beupdated. Else infinite loop!here3’sback!
    • 63 of 81Module 6 : Flow controlpass• It has no effects (do nothing), but helpindicates an empty statement/suite/blockWe add else: and passNochange!
    • 64 of 81Module 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
    • 65 of 81Module 6 : Flow controlCase Study: Path of a projectile• In many computer games, we can see parabolas,which are the trajectories of throwing objectsBut how to compute a parabola?From http://www.youtube.com/watch?v=bNNzRyd1xz0You are advised to try and go through thisexample yourself with Python and Excel
    • 66 of 81Module 6 : Flow controlInput and coordinate system• First, what is our input?• Let’s say:u – initial velocitya – angle• 2D Coordinate System:x – along horizony – height0yxuhorizonaxy ua
    • 67 of 81Module 6 : Flow controlInitial velocity along x and y• In Physics, we know that we can decomposeu into two components (vector decomposition):ux – initial velocity along x, which is u cos(a)uy – initial velocity along y, which is u sin(a)u sin(a) uau cos(a)
    • 68 of 81Module 6 : Flow controlThe Physics• First, let’s look at the Physics…• We can use the following formula:s = u t + ½ a t2where• s = distance travelled (in m)• u = initial velocity (in ms-1)• t = time (in s)• a = acceleration (in ms-2)(unit: m – meter, s – second)
    • 69 of 81Module 6 : Flow controlThe Physics• Along x, we assume no external forces, i.e.,a = 0Thus, traveled distance along x at time t is:x = ux t• Along y, we have gravity, and so, we put a = g,which is the gravitational field constant:a = g = -9.8ms-2Thus, traveled distance along x at time t is:y = uy t – 4.9 t2
    • 70 of 81Module 6 : Flow controlTo compute the parabola…• To compute the parabola, we need looping toincrementally compute the x and y locations ofthe object over timeMore important things…• Loop control variable: time t and t starts from 0• When to stop?Ans: object reaches the ground again or y < 0(of course, you may have more complicatedstopping criteria, say hitting an object)
    • 71 of 81Module 6 : Flow controlImplementation #1: Initialization(note: implementation continues on in next page)How detail we computethe parabola path; changethis value yourself and tryNeed radian forcos and sinNeed math module
    • 72 of 81Module 6 : Flow controlImplementation #2: Loop(note: implementation continues from previous page)Report parabola coordinatesUpdate loop control variable
    • 73 of 81Module 6 : Flow controlResults• A long list of coordinates, output in IDLE shellHow can we knowthat the computedparabola is correct?Perhaps error here?How to verify?
    • 74 of 81Module 6 : Flow controlVerify… Plot it with Excel #1• We can first select the coordinate outputs (withmouse) in IDLE and click copy in IDLE• Then, we can open a text editor, and paste thecoordinates into a brand-new text file as follows:
    • 75 of 81Module 6 : Flow controlVerify… Plot it with Excel #2• After that, we may load the text file into Excelas a space-delimited text file:Open the text file by Excelcheck delimited, and nextThen check space, nextand finish
    • 76 of 81Module 6 : Flow controlVerify… Plot it with Excel #3• Then, we can use the graph plotting function inExcel to plot the two lists of coordinates:yxI just use XY scatter plot
    • 77 of 81Module 6 : Flow controlMore to try…• You can change the initial velocity and plot moreseries in the same plot: u = 100,80,60When you verify, you have to askyourselves “Does it make sense?”
    • 78 of 81Module 6 : Flow controlOr… to try…• You can change the initial angle and plot moreseries in the same plot: a = 45,60,75What is the angle for the optimal distance along X?You can try the code (or try implement yourself) on Edventure
    • 79 of 81Module 6 : Flow controlTake Home Messages• General structure of a loop:– Initialize; Test; Loop body; Update• Concepts: loop control variable, counter-controlled andsentinel-controlled loops, nested loops• Syntax: while, for, and range• Reminders:– Dry run and check the number of iterations!!!One more or one less iteration can kill the program… bug!!!– Understand how and when to stop!!!– Use break and continue very carefully!!!– Read (trace code and logic) and try (work it out) more examples...– Always test and verify your codeThink and try test data that causes different consequences!!!Practice! Practice!! Practice!!!
    • 80 of 81Module 6 : Flow controlMore…• Again the four levels of skillslike module 6.1– #1 Understand: trace andunderstand code: control flow– #2 Analysis: Given a problem,think and analyze carefully thelogic– #3 Apply: Transform the logicappropriately into for or while loops– #4 Test: test data to evaluate withdifferent consequences• Practice!Practice!!Practice!!!What is/are to be printed out?
    • 81 of 81Module 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. Note:other than using Excel, Python has modulepylab for graph plotting (see 2.4)