81
Introduction to Computational Thinking Module 6 : Flow control #2 Asst Prof ChiWing FU, Philip Office: N402c104 email: cwfu[at]ntu.edu.sg

Lecture 6.2 flow control repetition

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Lecture 6.2  flow control repetition

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

Page 2: Lecture 6.2  flow control repetition

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

Page 3: Lecture 6.2  flow control repetition

3 of 81Module 6 : Flow control

Basic Concepts• Recall the motivation example to compute

average student height in a class

Page 4: Lecture 6.2  flow control repetition

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

Page 5: Lecture 6.2  flow control repetition

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)

Page 6: Lecture 6.2  flow control repetition

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

Page 7: Lecture 6.2  flow control repetition

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

Page 8: Lecture 6.2  flow control repetition

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

Page 9: Lecture 6.2  flow control repetition

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

Page 10: Lecture 6.2  flow control repetition

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

Page 11: Lecture 6.2  flow control repetition

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

Page 12: Lecture 6.2  flow control repetition

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

Page 13: Lecture 6.2  flow control repetition

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

Page 14: Lecture 6.2  flow control repetition

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

Page 15: Lecture 6.2  flow control repetition

15 of 81Module 6 : Flow control

Any difference? Try them!!!

Order is importantThe control FLOW!!!

Indentation is importantIt defines a block

Page 16: Lecture 6.2  flow control repetition

16 of 81Module 6 : Flow control

Example #1.1• Compute and print a conversion table between

Fahrenheit and Celsius, starting from 0 deg. C

Page 17: Lecture 6.2  flow control repetition

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

Page 18: Lecture 6.2  flow control repetition

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)

Page 19: Lecture 6.2  flow control repetition

19 of 81Module 6 : Flow control

Check loop iteration: table

False122.0

44.4True112.0

………

5.6True42.0

0True32.0

Output Celsiusfahren < tempLimitfahren

Page 20: Lecture 6.2  flow control repetition

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?

Page 21: Lecture 6.2  flow control repetition

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

Page 22: Lecture 6.2  flow control repetition

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

Page 23: Lecture 6.2  flow control repetition

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

Page 24: Lecture 6.2  flow control repetition

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

Page 25: Lecture 6.2  flow control repetition

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

Page 26: Lecture 6.2  flow control repetition

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

Page 27: Lecture 6.2  flow control repetition

27 of 81Module 6 : Flow control

Python Syntax: while with else

Page 28: Lecture 6.2  flow control repetition

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

Page 29: Lecture 6.2  flow control repetition

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

Page 30: Lecture 6.2  flow control repetition

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…

Page 31: Lecture 6.2  flow control repetition

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

Page 32: Lecture 6.2  flow control repetition

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

Page 33: Lecture 6.2  flow control repetition

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 ] ?

Page 34: Lecture 6.2  flow control repetition

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?

Page 35: Lecture 6.2  flow control repetition

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

Page 36: Lecture 6.2  flow control repetition

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…

Page 37: Lecture 6.2  flow control repetition

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)

Page 38: Lecture 6.2  flow control repetition

38 of 81Module 6 : Flow control

Example #2.1• Problem: print a multiplication table of a certain

number, e.g., 9, see below:

Page 39: Lecture 6.2  flow control repetition

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

Page 40: Lecture 6.2  flow control repetition

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

Page 41: Lecture 6.2  flow control repetition

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

Page 42: Lecture 6.2  flow control repetition

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

Page 43: Lecture 6.2  flow control repetition

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

Page 44: Lecture 6.2  flow control repetition

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)

Page 45: Lecture 6.2  flow control repetition

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

… …

Page 46: Lecture 6.2  flow control repetition

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

Page 47: Lecture 6.2  flow control repetition

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!!!

Page 48: Lecture 6.2  flow control repetition

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?

Page 49: Lecture 6.2  flow control repetition

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?

Page 50: Lecture 6.2  flow control repetition

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?

Page 51: Lecture 6.2  flow control repetition

51 of 81Module 6 : Flow control

Case study: Example #2.5• Implementation

Page 52: Lecture 6.2  flow control repetition

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

Page 53: Lecture 6.2  flow control repetition

53 of 81Module 6 : Flow control

More Patterns?• Can you write programs

to print out each of these patterns?

Page 54: Lecture 6.2  flow control repetition

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

Page 55: Lecture 6.2  flow control repetition

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

Page 56: Lecture 6.2  flow control repetition

56 of 81Module 6 : Flow control

What are break and continue?• Print out of running this program

Page 57: Lecture 6.2  flow control repetition

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

Page 58: Lecture 6.2  flow control repetition

58 of 81Module 6 : Flow control

break• And break is considered as an abnormal exit

from the loop… so?

No morehere3!

Page 59: Lecture 6.2  flow control repetition

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

Page 60: Lecture 6.2  flow control repetition

60 of 81Module 6 : Flow control

continue• To understand continue…

Let’s go back to the basic example:

Page 61: Lecture 6.2  flow control repetition

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

Page 62: Lecture 6.2  flow control repetition

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!

Page 63: Lecture 6.2  flow control repetition

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!

Page 64: Lecture 6.2  flow control repetition

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

Page 65: Lecture 6.2  flow control repetition

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

Page 66: Lecture 6.2  flow control repetition

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

Page 67: Lecture 6.2  flow control repetition

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)

Page 68: Lecture 6.2  flow control repetition

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)

Page 69: Lecture 6.2  flow control repetition

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

Page 70: Lecture 6.2  flow control repetition

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)

Page 71: Lecture 6.2  flow control repetition

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

Page 72: Lecture 6.2  flow control repetition

72 of 81Module 6 : Flow control

Implementation #2: Loop

(note: implementation continues from previous page)

Report parabola coordinates

Update loop control variable

Page 73: Lecture 6.2  flow control repetition

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?

Page 74: Lecture 6.2  flow control repetition

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:

Page 75: Lecture 6.2  flow control repetition

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

Page 76: Lecture 6.2  flow control repetition

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

Page 77: Lecture 6.2  flow control repetition

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?”

Page 78: Lecture 6.2  flow control repetition

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

Page 79: Lecture 6.2  flow control repetition

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!!!

Page 80: Lecture 6.2  flow control repetition

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?

Page 81: Lecture 6.2  flow control repetition

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)