L06 - Flow Control - While Loop and Basic For Loop

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Introduction to Programming

Semester 1, 2021
Lecture 6,
Control Flow - While Loop and Basic For Loop

Slides based on material by John Stavrakakis and that provided for


Sedgewick . All rights reserved
Copyright Warning

COMMONWEALTH OF AUSTRALIA

Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or


on behalf of the University of Sydney pursuant to Part VB of the
Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright


under the Act. Any further reproduction or communication of this
material by you may be the subject of copyright protection under
the Act.

Do not remove this notice.

2
Week 4: Control Flow - While Loop

We will cover: While loop, including nested while loop. Basic for loop
through a range of numbers.
You should read: §§1.3 of Sedgewick

3
Previously in INFO1110...if...else i f

speed false
<= 60

true
speed false
fine = 0
<= 70

true false

fine = 109 speed


<= 80
true
speed false
fine = 254
<= 90

true

fine = 835 fine = 2252

4
Previously on INFO1110...if...else i f

How many possible paths of code?

speed false
<= 60

true
speed false
fine = 0
<= 70

true false

fine = 109 speed


<= 80
true
speed false
fine = 254
<= 90

true

fine = 835 fine = 2252

5
Lecture 6: While Loops and For Loops

6
while

Steps of while :

1 while (condition) do
2 · statement

1 condition is checked: if it is true then go on to Step 2


2 statement is executed, then go on to Step 1

The while loop continues until condition is checked at Step 1 is false.

7
while loop diagram

false 1
begin with the condition
condition 2
Check the condition
3
if it’s true, execute the statement;
true otherwise, exit the loop
4
go back to the condition
statement(s)

8
while loop example

i=0
i
false
condition false
i <5

true
true

statement(s)
i=i+1

9
while loop diagram to code

i=2
code?

false
i < 10

true

i=i-1

i=i*5

10
while loop desk checking

i=2

false
i < 10

true

i=i-1

i=i*5

11
while loop desk checking

What is the final value of i?

How many iterations will there be in total?

12
while loop desk check
distance = 0.0
distance walking
walking = true
0 T
walking false

true
distance =
distance + 10

distance false
> 42.5

true

walking = false

13
while

“While the condition is true, repeat what’s in the statement.”

Steps of while:

1 while (condition) do
2 · statement

 condition is checked: if it is true then go on to Step 2


 statement is executed, then go on to Step 1

The while loop continues until condition is checked at Step 1 is false.

Python Syntax:
while condition :
statement
14
while example

1 bucket_ capacity = 5.0


2 bucket_ filled = 0.0
3 sand_ handful = 0.20
4
5 while bucket_ filled < bucket_ capacity :
6 bucket_ filled = bucket_ filled + sand_ handful
7 print(" bucket_ filled = " + str( bucket_ filled ))

How many iterations do you expect ?

15
while ( t r u e )

while True would imply an infinite loop

1 number = 1
2 while True:
3 p r i n t ( number)
4 number = number + 1

break ; is a statement used to leave the body of a loop

16
break

false
condition
• break is a special reserved word
• When used in loops, it means
“break from the current iteration of true
optional
this loop”
statements…
• It isn’t allowed in an if statement.
break

optional
statements…

17
break example

distance = 0.0

false
true

true

distance =
distance + 10

distance false
> 72.5

true

break

18
continue

false
• continue is a special reserved word condition
• When used in loops, it means “skip the
rest of this iteration and go on to the true
next one”
optional
• It is only allowed inside the body of a statements…
loop.
continue

optional
statements…

19
while loop with break and continue

Control flow within loops


false
condition • if the break statement is
false executed then exit the loop
condition
true • if the continue statement is
optional executed then operation of
statements… true
optional the loop goes back to the
break statements… beginning of the loop
optional continue
statements…
optional
statements…

20
Code trace: break and continue — example

1 x=4
2 y = 20
3 while x < y:
4 x += 1
5 if x % 2 == 0:
6 continue
7 print(" x = " + str( x))
8 if x == 13:
9 break
10 print(" All done!")

21
1
x=4 ~> python Continuing.py
2
y = 20 x =5
3 while x < y: x =7
4 x += 1
x =9
5 if x % 2 == 0:
6 continue
x = 11
7 print(" x = " + str( x)) x = 13
8 if x == 13: A l l done!
9 break
10 print(" All done!")

22
Nested loopexample

friends = 1 friends digits

friends < false


1 0
5

true

friends =
friends + 1

digits = 0

digits < false


4

true

digit = digit + 1

23
Nested loopexample

friends = 1

friends < false


5

true

friends =
friends + 1

digits = 0

digits < false


4

true

digit = digit + 1

24
Basic For Loops
While loop revisited
while loop is simple and good
only need to consider the condition, when the loop keeps going or stops
other code can contribute to the setup and change in the loop condition
e.g. a counter variable initialised, checked, updated, checked, updated,
checked, etc.
1 # initilise
2 counter = 0
3 while counter < 10:
4 # do something in each iteration
5 ...
6 # move toward the end of loop condition
7 counter = counter + 1;

Most loops follow a general structure, can be shortened as a for loop


Know your while loops!

26
for
Know your while loops!

The easy version:


for loops and the range( ) Function

Syntax:
E.g. for i in range (6) :

• The for keyword


• A variable name
• The in keyword
• A call to the range( ) method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)

27
for (cont.)

1 # initilise a variable as a counter


2 counter = 0
3
# condition check for whether to continue/stop
4 while counter < 10:
5 # do something in each iteration
6 ...
7 # increment the counter toward the end of loop condition
8 counter = counter + 1;

Rewrite the above while loop using for loop


1 # initilise, condition check, and increment in one line (but in different iterations)
2 for counter in range(9):
3 # do something in each iteration
4 ...

28
range

Common sequences can be constructed using range

1 f o r num i n r a n g e ( 5 ) :
2 p r i n t ( " t h e v a l u e o f num i s " + s t r ( num ) )

the value of num is 0


the value of num is 1
the value of num is 2
the value of num is 3
the value of num is 4

29
range (cont.)

range(start, s t o p , step)

The first argument


– where the for loop’s variable starts

The second argument


– will be up to, but NOT including, the number to stop

The third argument


– will be the step argument.

30
range (cont.)

range(start, s t o p , step)

Useful for any counting of iterations to perform.


1 f o r num i n r a n g e ( 1 0 , 5 , - 1 ) :
2 p r i n t ( " t h e v a l u e o f num i s " + s t r ( num ) )

the value of num is 10


the value of num is 9
the value of num is 8
the value of num is 7
the value of num is 6

31
for vs while
Which do I choose?

How many iterations do you need? if you know the answer to this
question in advance, a for loop is suitable

32

You might also like