# CSC1015F – Loop Structures Michelle Kuttel

## Presentation on theme: "CSC1015F – Loop Structures Michelle Kuttel"— Presentation transcript:

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

Control structures Loops 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

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

For statement (Chapter 2 in textbook)  definite loop in Python: for in : 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

Checkpoint 1: write down the exact output of this code for sq in [0, 1, 2, 3]: print(sq*sq,end=‘,’) 5

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

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( ) will produce a sequence of numbers that starts with 0 and goes up to, but does not include, 7

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

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

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

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

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

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

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

range examples range(5) # a = 0,1,2,3,4 range(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

Checkpoint 3: What is the exact output of the following? for i in range(1,5): print('#'*i) 16

17 Loops (see square.py)  Squares… *** H=3 *** **** H=4 **** ***** H=5 ***** ** H=2 **

Checkpoint 4: Write a function tri() that works (using a loop) as follows: tri(3,'^') ^^^ ^^ ^ tri(4,'m') mmmm mmm mm m tri(6,'@') @@@@@@ @@@@@ @@@@ @@@ @@ @ 18

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

Augmented Assignment Expressions 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

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

Python Programming, 2/e 22 More from the textbook Accumulating Results: Factorial Say 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.

Python Programming, 2/e 23 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 variable Loop until final result is reached update the value of accumulator variable

Program to calculate the average of a series of numbers entered by user – 1. Accumulator as well  Algorithm: Input the count of the numbers, n Initialise sum to 0 Loop n times Input a number, x Add x to sum Output average as sum divided by n 24

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

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

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

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

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 : i=0 while i<= 10: print(i) i=i+1 29 for i in range(11): print(i) has same effect as :

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 : i=0 while i<= 10: print(i) i=i+1 30

Checkpoint #7: while loop 31 #Checkpoint_while.py i,inc=1,1 while i<20: print(i) i= i+inc inc+=2  What is the exact output of the following code?

Checkpoint 7b.py  What will this do? [run it in the shell] i=0 while i<= 10: print(i) i=i-1 32

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

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

Boolean expressions while response==“y” or response ==“Y” is OK but while response==“y” or “Y” is an infinite loop. Why? 35

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

Common loop patterns #1: Interactive loops  Average2.py  Is this an optimal solution? 37

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 valuesSentinel

Common loop patterns #3: Sentinel loops  Average3.py 39

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

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

Nested loops You 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

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

Checkpoint #8: nested for loop 44 #Checkpoint_nested_for.py for i in range(3): for j in range(3): print(i,j, sep=“,”,end=' ') print()  What is the exact output of the following code?

Checkpoint #9: nested while loop 45 #Checkpoint_nested_for.py for 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

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

Checkpoint #10: continue  What is the exact output of the following code? - 47 #Checkpoint10.py for i in range(3): for j in range(3): if i==j: continue print(i,j, sep=',',end=' ') print()

Checkpoint #11: break  What is the exact output of the following code? - 48 #Checkpoint11.py for i in range(4): for j in range(4): if i==j: break print(i,j, sep=',',end=' ') print()

Example: Restaurant2.py (improved) def displayName(): print("--------------------------------") print(" Roadkill Grill ") print(" 'You kill it, we grill it!'") print("--------------------------------") def displayMenu(): print(1,'warthog',50.99) print(2,'squirrel',10.50) print(3,'rat',1.99) print(4,'UFA (Unidentified Flattened Animal)',60) def main(): displayName() while True: displayMenu() choice = input("\nPlease make a selection (1,2,3 or 4):") if choice=='1' or choice=='2' or \ choice == '3' or choice == '4': print("Good choice! My favourite!") break print("Not on the menu - sorry. Try again.") main() 49

Checkpoint 9b: Explain in English what this code does import random ans = random.randint(1,10) while True: x = eval(input("Guess:")) if x==ans: break print("Wrong! Try again.") print("Correct!") 50

Checkpoint 9c: Explain in English what this code does import 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': break 51

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

Other loop patterns: Read in text book. Post test loop while True: ….exit with a break How would you do the average program with a post-test loop? Average4.py 53

Other loop patterns: Read in text book. Loop and a half while True: ….exit with a break Average program with a loop and-a-half: Average5.py 54

KiddyMaths4.py import random def test(num_questions): num_correct=0 for i in range(num_questions): a = random.randint(1,10) b = random.randint(1,10) ans = a*b txt=" {0} x {1} = " x = input(txt.format(a,b)) if not x or not x.isdigit() : break if eval(x) == ans: print("correct!") num_correct+=1 else: print("Wrong! Correct answer is:",ans) else: print(num_correct,"/",num_questio ns) if __name__ == '__main__': test(5) 55

Post-test loop import 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

Loop-and-a-half import 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