1 of 81Module 6 : Flow control
Introduction to Computational Thinking
Module 6 : Flow control #2
Asst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104
email: cwfu[at]ntu.edu.sg
2 of 81Module 6 : Flow control
Topics• 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 control
Basic Concepts• Recall the motivation example to compute
average student height in a class
4 of 81Module 6 : Flow control
Basic Concepts• With the looping mechanism, we can
repeat certain code arbitrarily number of times based on the need
5 of 81Module 6 : Flow control
General structure of a loopGenerally, four steps:1. Initialize: loop control variable
2. Test: continue the loop or not?
3. Loop body: main computation being repeated
4. Update: modify the value of loop control variable so that next time when we test, we MAY exit the loop
Sometimes a loop may not have all of them,e.g., infinite loop (test is always true)
6 of 81Module 6 : Flow control
General structure of a loopVisualize them by a flow chart!!!
1. Initialize2. Test3. Loop body4. Update
Initialize
Statement
Update
Testtrue
false
4
3
2
1
Loop
7 of 81Module 6 : Flow control
main:SET sum TO 0 // InitializeSET counter TO 0WHILE counter < N // Test
READ height // Loop bodyADD height TO sumINCREMENT counter BY 1 // Update
ENDWHILECOMPUTE average = sum/counterPRINT average
General structure of a loopExample: Compute average height of N students
12
3
4
8 of 81Module 6 : Flow control
Two kinds of loop1. Counter-controlled loop – the number of
repetitions is known before the loop starts execution; just repeat the loop on each element in a preset sequence
2. Sentinel-controlled loop – the number of repetitions is NOT known before the loop starts. For example, a sentinel value (e.g., –1, different from the regular data) is used to determine whether to execute the loop body
9 of 81Module 6 : Flow control
Examples:• Counter-controlled loops
Compute average student height in a class…
Assumption: we know the number of students before we start the loop
10 of 81Module 6 : Flow control
Examples:• Sentinel-controlled loops
Compute average height of people entering Canteen A in a day…
sum = count = 0time = get current timeWHILE time < Canteen A closing time
height = get height of next guysum += heightcount += 1time = get current time
END WHILE
Cannot know ahead how many people entering canteen A before we start the loop body
11 of 81Module 6 : Flow control
Examples:• A Sentinel-controlled loop
usually contains all four loop elements
InitializeTest
Loop Body
UpdateNote: time is the loop control variable
12 of 81Module 6 : Flow control
In PythonWe can implement loops by:• for – usually for counter-controlled loops• while – usually for sentinel-controlled
loop, but may also be used to implement counter-controlled loops
13 of 81Module 6 : Flow control
Topics• 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 control
Python Syntax: while• Similar to an IF statement but repeat the
block till the condition becomes falseSyntax:while <boolean expression> :
suite (one or moreindented statements)
Example:while a > b:print(a," > ",b)a = a - 10
MUST use colon followedby proper indentation
the wholewhile structure
Test
true
Statement
false
15 of 81Module 6 : Flow control
Any difference? Try them!!!
Order is importantThe control FLOW!!!
Indentation is importantIt defines a block
16 of 81Module 6 : Flow control
Example #1.1• Compute and print a conversion table between
Fahrenheit and Celsius, starting from 0 deg. C
17 of 81Module 6 : Flow control
Print message
Read tempLimit
Start
fahren = 32.0
fahren<=tempLimit ?
true
fahren += 10
Print fahren, celsius
false
End
Initialize
while (Test)Statement
Update
Loop Body
Test
celsius = (fahren– 32.0) * 5.0 / 9.0
18 of 81Module 6 : Flow control
Implementation
• Who is the loop control variable?• Counter-controlled or sentinel-controlled?
Note: You will learn how to format the output as below for print() by using % in module 8 on Strings
\t - a tab space (nicer formatting)
19 of 81Module 6 : Flow control
Check loop iteration: table
False122.0
44.4True112.0
………
5.6True42.0
0True32.0
Output Celsiusfahren < tempLimitfahren
20 of 81Module 6 : Flow control
Any 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 control
Example #1.2• Maybe… we can force the user to input
again? But how?• Idea:
• Keep asking until he/she enters a number that is at least 32 and at most a certain reasonable limit
•Now… we can add a while loop
22 of 81Module 6 : Flow control
ImplementationNew while
In the new loop:• Who is the loop control variable?• Counter-controlled or sentinel-controlled?
( ) is ok butredundant
23 of 81Module 6 : Flow control
Note:• while loop is useful if we want to
repeatedly ask user for input until the input fulfills our requirement
24 of 81Module 6 : Flow control
Example #1.3• Write a program to read numbers from
user; sum them up until the input is -1 (sentinel value)
Indicate an end
25 of 81Module 6 : Flow control
Implementation• Again, we can use while loop to
continue 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 control
Python Syntax: while with else• while loop, oddly, can have an associated else statement
• else statement is executed when the loop finishes under normal conditions• The last thing the loop does as it exits
• Syntax:while booleanExpression:
suite1else:
suite2rest of the program
the wholewhilestructure
27 of 81Module 6 : Flow control
Python Syntax: while with else
28 of 81Module 6 : Flow control
Topics• 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 control
range• Before we discuss "for" loop, we first
learn a useful built-in function in Python called range()•Note: range() is often used in "for" loop
30 of 81Module 6 : Flow control
What is range?• Generates a list of integers from start up to end (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 control
Meaning• 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 rather than an explicit list; we can use list to see its contents, see next page
32 of 81Module 6 : Flow control
count down
Infinite! returns an empty list (“list” is a
Error! Only integers!
start from 0 and step 1
sequence)
returns a memory efficient object
33 of 81Module 6 : Flow control
Exercises 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 control
What is memory efficient object?• range() returns a “range object” (memory
efficient object) that pretends to be the sequence• It is an opaque sequence which yields the same
values as "list(range())”,but NOT storing every single value explicitly; it generates values for you only 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 control
Topics• 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 control
Python Syntax: for• Control flow: loop through the objects
according to their order in the sequenceSyntax:for <element> in <sequence> :
suite (one or more indented statements)
Example:
for each element in it
two forstructures
can be a list also…
37 of 81Module 6 : Flow control
Note:Main issue:• Variable x (or y) in the example “for” loops will take
different values in different loop iterations
Other 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 control
Example #2.1• Problem: print a multiplication table of a certain
number, e.g., 9, see below:
39 of 81Module 6 : Flow control
Example #2.1 – Algorithm?• First, ask user for a number• Then, loop from 1 to 10, compute the
multiplication, and display the formulae
40 of 81Module 6 : Flow control
Example #2.1 – Implementation• In Python, just a few lines…
Use comma to separate different elements for printEnd with 11 instead
of 10 if we want the last value to be 10
41 of 81Module 6 : Flow control
Case Study: Example #2.2• Summing a series of data using for loop
!10
x
!4
x
!3
x
!2
x
1!
x1
10432
+−+−+− LL
Basic 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 control
Case Study: Example #2.2• Let’s analyze the term
Observation:• 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……
!10
x
!4
x
!3
x
!2
x
1!
x1
10432
+−+−+− LL
43 of 81Module 6 : Flow control
Case Study: Example #2.2• More detailed idea to implement it
So...• We may have one variable to keep track of the term,
say term• One more variable to keep track of what to be
divided next, say divisor• Another variable to accumulate the sum, say total
!10
x
!4
x
!3
x
!2
x
1!
x1
10432
+−+−+− LL
44 of 81Module 6 : Flow control
Case Study: Example #2.2• Hence, we have:
Note:- Make sure use float forx and term
- The negative sign beforeterm can flip the sign of the term in each iteration
- I put in this “print(term)”for testing purpose;note: testing is important to verify your code!!!(after that, can just comment it)
45 of 81Module 6 : Flow control
Inputs/initialization:x = 0.9, total= 1.0, term = 1.0
Case Study: Example #2.2• We can trace each iteration to verify also:
Outputs:Result = 0.406569
…
+1
-1
sign
0.4065699.609e-0810
…
0.5050.4052
0.0999-0.91
totaltermdivisor
… …
46 of 81Module 6 : Flow control
Topics• 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 control
Nested Loops• Sometimes… one level of loop is not sufficient
for the algorithmic need; an outer loop may enclose an inner loop (or even more), e.g.,
Two levels of loops!!!
48 of 81Module 6 : Flow control
Example #2.3• Note: This additional argument is used in
Python 3 to avoid the default ending \n
This is the entiresuite/block insidethe outer for loop
Only one statement inside the inner for loop
Question:How many times each print is executed?What is the control flow?
49 of 81Module 6 : Flow control
Case study: Example #2.4• Printing the full Multiplication Table
Print out fromthe program:
How many times each of these print statements is executed?
50 of 81Module 6 : Flow control
Case study: Example #2.5• Print a pattern, e.g., triangular pattern:
First… observe and analyze the pattern…How many stars on each level?How many leading white spaces?
51 of 81Module 6 : Flow control
Case study: Example #2.5• Implementation
52 of 81Module 6 : Flow control
Case study: Example #2.5.1• Use while loops inside instead
How many times these print functions are called?
Changeto
while
53 of 81Module 6 : Flow control
More Patterns?• Can you write programs
to print out each of these patterns?
54 of 81Module 6 : Flow control
Topics• 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 control
What are break and continue?• Python keywords that can alter control flow
in 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 control
What are break and continue?• Print out of running this program
57 of 81Module 6 : Flow control
break• Meaning: Executing break exits the immediate
loop that contains it
Compared to prev. page:We add if and break
Control flow knowledge:Go after the whole enclosing loop
58 of 81Module 6 : Flow control
break• And break is considered as an abnormal exit
from the loop… so?
No morehere3!
59 of 81Module 6 : Flow control
break• How if we include everything in a for loop?
This time, we add the outer forBasically a for statement
The print-out doubled!!Note: break affects only theinner loop that contains it
60 of 81Module 6 : Flow control
continue• To understand continue…
Let’s go back to the basic example:
61 of 81Module 6 : Flow control
continue• Skips the rest of the loop body and goes back to
the test in the loop that contains it
Compare to prev. page:We add if and continue
Control flow knowledge:Go immediately to test
in the enclosing loop
62 of 81Module 6 : Flow control
continue• If we run the program, print “here2” will only
be reached two times… why?
For continue, make sureloop control variable can be updated. Else infinite loop!
here3’sback!
63 of 81Module 6 : Flow control
pass• It has no effects (do nothing), but help
indicates an empty statement/suite/block
We add else: and pass
Nochange!
64 of 81Module 6 : Flow control
Topics• 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 control
Case Study: Path of a projectile• In many computer games, we can see parabolas,
which are the trajectories of throwing objects
But how to compute a parabola?From http://www.youtube.com/watch?v=bNNzRyd1xz0
You are advised to try and go through this example yourself with Python and Excel
66 of 81Module 6 : Flow control
Input and coordinate system• First, what is our input?• Let’s say:
u – initial velocitya – angle
• 2D Coordinate System:x – along horizony – height
0
y
x
u
horizona
x
y u
a
67 of 81Module 6 : Flow control
Initial velocity along x and y• In Physics, we know that we can decompose
u 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) u
au cos(a)
68 of 81Module 6 : Flow control
The Physics• First, let’s look at the Physics…• We can use the following formula:
s = u t + ½ a t2
where• 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 control
The 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-2
Thus, traveled distance along x at time t is:y = uy t – 4.9 t2
70 of 81Module 6 : Flow control
To compute the parabola…• To compute the parabola, we need looping to
incrementally compute the x and y locations of the object over time
More 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 complicated stopping criteria, say hitting an object)
71 of 81Module 6 : Flow control
Implementation #1: Initialization
(note: implementation continues on in next page)
How detail we computethe parabola path; changethis value yourself and try
Need radian forcos and sin
Need math module
72 of 81Module 6 : Flow control
Implementation #2: Loop
(note: implementation continues from previous page)
Report parabola coordinates
Update loop control variable
73 of 81Module 6 : Flow control
Results• A long list of coordinates, output in IDLE shell
How can we know that the computedparabola is correct?Perhaps error here?How to verify?
74 of 81Module 6 : Flow control
Verify… Plot it with Excel #1• We can first select the coordinate outputs (with
mouse) in IDLE and click copy in IDLE• Then, we can open a text editor, and paste the
coordinates into a brand-new text file as follows:
75 of 81Module 6 : Flow control
Verify… Plot it with Excel #2• After that, we may load the text file into Excel
as a space-delimited text file:
Open the text file by Excel check delimited, and next
Then check space, next and finish
76 of 81Module 6 : Flow control
Verify… Plot it with Excel #3• Then, we can use the graph plotting function in
Excel to plot the two lists of coordinates:
y
x
I just use XY scatter plot
77 of 81Module 6 : Flow control
More to try…• You can change the initial velocity and plot more
series in the same plot: u = 100,80,60
When you verify, you have to askyourselves “Does it make sense?”
78 of 81Module 6 : Flow control
Or… to try…• You can change the initial angle and plot more
series in the same plot: a = 45,60,75
What 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 control
Take Home Messages• General structure of a loop:
– Initialize; Test; Loop body; Update• Concepts: loop control variable, counter-controlled and
sentinel-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 code
Think and try test data that causes different consequences!!!
Practice! Practice!! Practice!!!
80 of 81Module 6 : Flow control
More…• Again the four levels of skills
like module 6.1– #1 Understand: trace and
understand code: control flow– #2 Analysis: Given a problem,
think and analyze carefully the logic
– #3 Apply: Transform the logic appropriately into for or while loops
– #4 Test: test data to evaluate with different consequences
• Practice!Practice!!Practice!!!
What is/are to be printed out?
81 of 81Module 6 : Flow control
Reading Assignment • Textbook
Chapter 2: Control2.1 to 2.4
Note: Though some material (2.3 and 2.4) in textbook is not directly related to the lecture material, you can learn more from them. Note: other than using Excel, Python has module pylab for graph plotting (see 2.4)