CSC1015F – Loop Structures Michelle Kuttel [email protected].

57
CSC1015F – Loop Structures Michelle Kuttel [email protected]

Transcript of CSC1015F – Loop Structures Michelle Kuttel [email protected].

Page 1: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

CSC1015F – Loop Structures

Michelle Kuttel

[email protected]

Page 2: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Control structuresLoops are another way to alter the flow of a

program

Programmers use loops to repeat a sequence of statements multiple times in succession The code that is repeated in a loop is called the body of the loop

Each repetition of the loop body is called an iteration of the loop

2

Page 3: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Control structures

Simplest kind of loop is called a definite loop we know exactly how many times it will

execute or iterate

a Python for loop

3

Page 4: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

For statement (Chapter 2 in textbook) definite loop in Python:

for <var> in <sequence>:

<body>

<var> variable is the loop index e.g.for i in [0, 1, 2, 3]:

print(i)

for i in [2,4,5,10]:

print(i)

4

Page 5: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 1: write down the exact output of this codefor sq in [0, 1, 2, 3]:

print(sq*sq,end=‘,’)

5

Page 6: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

For statement example 2:The body of the loop will execute once for each

successive value in the list

The length of the list determines how many times the loop is executed

for sq in [2,3,4,5,6,7,8,9,10,11,12]:print(sq*sq)

6

Page 7: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

For statement examples 3:for sq in range(10):

print(sq*sq)

range is a built-in Python function for generating a sequence of numbers

range(<expr>) will produce a sequence of numbers that starts with 0 and goes up to, but does not include, <expr>

7

Page 8: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Count to a million example 1 (run in shell, not Wing)

8

Page 9: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Count to a million example 2 (run in shell, not Wing)

9

Page 10: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Example from textbook: Calculating the future value of an investment with compound interest Money in an account earns interest

After an initial deposit (principal), how much will your investment be worth 10 years from now?

Inputs: principal – money to be invested in rands percentage interest rate – as a floating point (decimal)

number

Output: Value of the investment 10 years in the future

10

Page 11: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Invest.py counted loop pattern#FutureV.py

#Program to calculate the future value of an 10-year investment

# assuming a fixed interest rate

#Author: M. Kuttel

principal = eval(input("Enter the initial principal: "))

apr = eval(input("Enter the annual interest rate: "))

for i in range(10):

principal = principal *(1 + apr)

print("The value in 10 years is:", principal)

11

Page 12: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Invest.py counted loop pattern#FutureV.py

#Program to calculate the future value of an 10-year investment

# assuming a fixed interest rate

#Author: M. Kuttel

principal = eval(input("Enter the initial principal: "))

apr = eval(input("Enter the annual interest rate: "))

for i in range(10):

principal = principal *(1 + apr)

print("The value in 10 years is:", principal)

alternative algorithm? - use formula F = P*(1 + apr)n

12

Page 13: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 2: What is the output of this program?def FN(length):

a= 1

b= 1

for i in range(length):

print(a)

a,b=b,a+b

FN(8)

13

Page 14: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

More about range The range function can take up to 3

parameters to generate various sequences

range(i,j [,stride]) represents a range of integers with values i to j-1. If the starting value is omitted, it’s taken to be

zero. An optional stride can also be given as a third

argument.

14

Page 15: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

range examplesrange(5) # a = 0,1,2,3,4range(1,8) # b = 1,2,3,4,5,6,7 range(0,14,3) # c = 0,3,6,9,12 range(8,1,-1) # d = 8,7,6,5,4,3,2

15

Page 16: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 3: What is the exact output of the following?

for i in range(1,5): print('#'*i)

16

Page 17: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

17

Loops (see square.py) Squares…

*** H=3

***

***

**** H=4

****

****

****

***** H=5

*****

*****

*****

*****

** H=2

**

Page 18: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 4: Write a function tri() that works (using a loop) as follows:

18

Page 19: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 5: What is the exact output when this module is run?#module mystery.py

def a(par1,par2):

gap=par1//2 #we need // here - why?

for i in range(0,par1,2):

print(' '*gap,end='')

print(par2*(i+1))

gap=gap-1 # can also write this as: gap-=1

def sq(H,char):

for i in range(H):

print(char*H)

if __name__ =='__main__':

a(5,'*')

19

Page 20: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Augmented AssignmentExpressions such as

x=x+1

x=x+2

occur so frequently in loops that Python has abbreviated forms for them. e.g:

a+=3 #equivalent to a=a+3

a-=3 #equivalent to a=a-3

a*=3 #equivalent to a=a*3

a/=3 #equivalent to a=a/3

a%=3 #equivalent to a=a%3

s+=“cat” #equivalent to s=s+”cat”20

Page 21: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 6: Using the functions in module mystery.py, how can we make this pattern? Write down the code.21

Page 22: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Python Programming, 2/e22

More from the textbookAccumulating Results: FactorialSay you are waiting in a line with five other

people. How many ways are there to arrange the six people?

720 the factorial of 6 (abbreviated 6!)

Factorial is defined as:n! = n(n-1)(n-2)…(1)

So, 6! = 6*5*4*3*2*1 = 720

Ensure that you read and understand this example.

Page 23: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Python Programming, 2/e23

Accumulating Results: Factorial This algorithm is known as an accumulator,

because we’re building up or accumulating the answer in a variable, known as the accumulator variable.

The general form of an accumulator algorithm looks like this:

Initialize the accumulator variableLoop until final result is reached

update the value of accumulator variable

Page 24: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Program to calculate the average of a series of numbers entered by user – 1.Accumulator as well Algorithm:

Input the count of the numbers, nInitialise sum to 0Loop n times

Input a number, xAdd x to sum

Output average as sum divided by n

24

Page 25: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Program to calculate the average of a series of numbers entered by user – 1. Program:

#Average1.py

#Program to calculate the average of a series of numbers typed in by user

#Author: M. Kuttel

n = eval(input("How many numbers do you have? "))

sum = 0

for i in range(n):

x=eval(input("Enter a number:"))

sum = sum + x

print("The average of those numbers is", sum/n)

25

Page 26: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Program to calculate the average of a series of numbers entered by user – 1. This is not the ideal solution – why?

#Average1.py

#Program to calculate the average of a series of numbers typed in by user

#Author: M. Kuttel

n = eval(input("How many numbers do you have? "))

sum = 0

for i in range(n):

x=eval(input("Enter a number:"))

sum = sum + x

print("The average of those numbers is", sum/n)

26

Page 27: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

From question in class You can have 2 loop indices:

for i,j in [[3,5],[4,4],[5,3]]:

print(i,j)

But you will need to understand lists (which comes later) to understand this

27

Page 28: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Loops Two kinds of loops

Counting loop or definite loop– Computer knows, when it

begins the loop, how many times to execute the body

– Counting loop statement in Python: for

Indefinite or conditional loop

– Computer stops the loop when a condition is no longer true

– Event-controlled loop statements in Python: while

Page 29: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Indefinite loops Keeps iterating until certain conditions are met

no guarantee ahead of time how many times it will iterate

Implemented using a while statement:

while <condition>:

<body>

i=0

while i<= 10:

print(i)

i=i+1

29

for i in range(11):print(i)

has same effect as:

Page 30: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Indefinite loops Note that the while loop has a test at the top

– it is a pre-test loop and will not execute AT ALL if the condition is false.

while <condition>:

<body>

i=0

while i<= 10:

print(i)

i=i+1

30

Page 31: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint #7: while loop

31

#Checkpoint_while.pyi,inc=1,1while i<20: print(i) i= i+inc inc+=2

What is the exact output of the following code?

Page 32: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 7b.py What will this do? [run it in the shell]

i=0

while i<= 10:

print(i)

i=i-1

32

Page 33: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Indefinite loops What will this do?

i=0

while i<= 10:

print(i)

i=i-1

INFINITE LOOP

how do we get out of them?33

Page 34: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

34

Infinite Loops

A while loop should be designed so that the value tested in the Boolean expression is changed in a way that eventually makes it false, and terminates the loop

If the Boolean expression remains true, then the loop will run forever, resulting in an infinite loop Loops that check for equality or inequality (==

or !=) are especially prone to this error and should be avoided if possible

Page 35: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Boolean expressions while response==“y” or response ==“Y”

is OKbut

while response==“y” or “Y”

is an infinite loop. Why?

35

Page 36: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

36

Common Loop Bugs The two most common kinds of loop errors

are unintended infinite loops and off-by-one errors An off-by-one error is when a loop repeats the loop

body one too many or one too few times This usually results from a carelessly designed

Boolean test expression Use of == in the controlling Boolean expression

can lead to an infinite loop or an off-by-one error

Page 37: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Common loop patterns #1:Interactive loops Average2.py

Is this an optimal solution?

37

Page 38: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Common loop patterns #2:Sentinel loops Sentinel loop

Sentinel: not data, but marks the end of data Sentinel loop: reads data values until sentinel

Example Average of a series of numbers terminated

by zero

10, 20, 30, 0

Data values Sentinel

Page 39: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Common loop patterns #3:Sentinel loops Average3.py

39

Page 40: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Common loop patterns #3:Sentinel loops Average3.py

How do we choose the sentinel? - Needs to be distinct from any possible correct value.

Improvement with empty strings: Average3B.py

40

Page 41: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Sentinel loop example: Throwing a coin until you get tails (or heads) Coin.py

41

Page 42: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Nested loopsYou can place one loop inside another – they

are then called nested loops When nested, the inner loop iterates from

beginning to end for each single iteration of the outer loop

42

Page 43: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Nested loops: minutes and seconds example #HMinSec.py - run in shell

43

Page 44: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint #8: nested for loop

44

#Checkpoint_nested_for.pyfor i in range(3): for j in range(3): print(i,j, sep=“,”,end=' ') print()

What is the exact output of the following code?

Page 45: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint #9: nested while loop

45

#Checkpoint_nested_for.pyfor i in range(3): for j in range(3): print(i,j, sep=',',end=' ') print()

#answer in Checkpoint9.py

rewrite this code as a set of while loops

Page 46: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Break and Continue Statements in loops The break statement breaks out of the

smallest enclosing for or while loop.

The continue statement continues with the next iteration of the loop.

46

Page 47: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint #10: continue What is the exact output of the following

code? -

47

#Checkpoint10.pyfor i in range(3): for j in range(3): if i==j: continue print(i,j, sep=',',end=' ') print()

Page 48: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint #11: break What is the exact output of the following

code? -

48

#Checkpoint11.pyfor i in range(4): for j in range(4): if i==j: break print(i,j, sep=',',end=' ') print()

Page 49: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Example: Restaurant2.py (improved)

49

Page 50: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 9b: Explain in English what this code doesimport random

ans = random.randint(1,10)

while True:

x = eval(input("Guess:"))

if x==ans: break

print("Wrong! Try again.")

print("Correct!")

50

Page 51: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Checkpoint 9c: Explain in English what this code doesimport random

while True:

ans = random.randint(1,10)

while True:

x = eval(input("Guess:"))

if x==ans: break

print("Wrong! Try again.")

print("Correct!")

a =input("Play again?(Y/N)")

if a=='n'or a=='N':

break51

Page 52: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Note: Else Clauses on Loops Loop statements may have an else clause

executed when the loop terminates through exhaustion of the list (with for)

or when the condition becomes false (with while), but not when the loop is terminated by a break

statement.

52

Page 53: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Other loop patterns: Read in text book. Post test loopwhile True:

….exit with a break

How would you do the average program with a post-test loop?

Average4.py

53

Page 54: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Other loop patterns: Read in text book. Loop and a halfwhile True:

….exit with a break

Average program with a loop and-a-half: Average5.py

54

Page 55: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

KiddyMaths4.py

55

Page 56: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Post-test loopimport random

txt=" {0} x {1} = "

a = random.randint(1,10)

b = random.randint(1,10)

ans = a*b

while True:

x = eval(input(txt.format(a,b)))

if x==ans: break #exit loop if answer correct

else: print("Wrong! Try again.")

print("Correct!")56

Page 57: CSC1015F – Loop Structures Michelle Kuttel mkuttel@cs.uct.ac.za.

Loop-and-a-halfimport random

txt=" {0} x {1} = "

a = random.randint(1,10)

b = random.randint(1,10)

ans = a*b

while True:

x = eval(input(txt.format(a,b)))

if x==ans: break #exit loop if answer correct

print("Wrong! Try again.")

print("Correct!")57