CSC 1015 F Loop Structures Michelle Kuttel mkuttelcs

  • Slides: 57
Download presentation
CSC 1015 F – Loop Structures Michelle Kuttel mkuttel@cs. uct. ac. za

CSC 1015 F – Loop Structures Michelle Kuttel mkuttel@cs. uct. ac. za

Control structures Loops are another way to alter the flow of a program Programmers

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

Control structures Simplest kind of loop is called a definite loop we know exactly

Control structures Simplest kind of loop is called a definite loop we know exactly how many times it will execute or iterate 3 a Python for loop

For statement (Chapter 2 in textbook) definite loop in Python: for <var> in <sequence>:

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

Checkpoint 1: write down the exact output of this code for sq in [0,

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

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

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

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

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

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

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

Example from textbook: Calculating the future value of an investment with compound interest Money in an account earns interest Inputs: After an initial deposit (principal), how much will your investment be worth 10 years from now? principal – money to be invested in rands percentage interest rate – as a floating point (decimal) number Output: 10 Value of the investment 10 years in the future

Invest. py counted loop pattern #Future. V. py #Program to calculate the future value

Invest. py counted loop pattern #Future. V. 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 #Future. V. py #Program to calculate the future value

Invest. py counted loop pattern #Future. V. 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=

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

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. 14 An optional stride can also be given as a third argument.

range examples range(5) # a = 0, 1, 2, 3, 4 range(1, 8) #

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,

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

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

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

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

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

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

Checkpoint 5: What is the exact output when this module is run? #module mystery. py def a(par 1, par 2): gap=par 1//2 #we need // here - why? for i in range(0, par 1, 2): print(' '*gap, end='') print(par 2*(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

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

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

More from the textbook Accumulating Results: Factorial Say you are waiting in a line

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. 22 Python Programming, 2/e

Accumulating Results: Factorial This algorithm is known as an accumulator, because we’re building up

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 23 Python Programming, 2/e

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

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 –

Program to calculate the average of a series of numbers entered by user – 1. Program: #Average 1. 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 –

Program to calculate the average of a series of numbers entered by user – 1. This is not the ideal solution – why? #Average 1. 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

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

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

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 has same effect as: for i in range(11): print(i)

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

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

Checkpoint #7: while loop What is the exact output of the following code? #Checkpoint_while.

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

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

Checkpoint 7 b. 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

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

Infinite Loops A while loop should be designed so that the value tested in

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

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

Common Loop Bugs The two most common kinds of loop errors are unintended infinite

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 36 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 Average 2. py Is this an optimal solution?

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

Common loop patterns #2: Sentinel loops Sentinel loop Sentinel: not data, but marks the

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, Data values 30, 0 Sentinel

Common loop patterns #3: Sentinel loops Average 3. py 39

Common loop patterns #3: Sentinel loops Average 3. py 39

Common loop patterns #3: Sentinel loops Average 3. py How do we choose the

Common loop patterns #3: Sentinel loops Average 3. py How do we choose the sentinel? - Needs to be distinct from any possible correct value. Improvement with empty strings: Average 3 B. py 40

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

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 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 #HMin. Sec. py - run in shell 43

Nested loops: minutes and seconds example #HMin. Sec. py - run in shell 43

Checkpoint #8: nested for loop What is the exact output of the following code?

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

Checkpoint #9: nested while loop rewrite this code as a set of while loops

Checkpoint #9: nested while loop rewrite this code as a set of while loops #Checkpoint_nested_for. py for i in range(3): for j in range(3): print(i, j, sep=', ', end=' ') print() #answer in Checkpoint 9. py 45

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

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? - #Checkpoint

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

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

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

Example: Restaurant 2. py (improved) def display. Name(): print("----------------") print(" Roadkill Grill ") print("

Example: Restaurant 2. py (improved) def display. Name(): print("----------------") print(" Roadkill Grill ") print(" 'You kill it, we grill it!'") print("----------------") def display. Menu(): print(1, 'warthog', 50. 99) print(2, 'squirrel', 10. 50) print(3, 'rat', 1. 99) print(4, 'UFA (Unidentified Flattened Animal)', 60) def main(): 49 display. Name() while True: display. Menu() choice = input("n. Please 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()

Checkpoint 9 b: Explain in English what this code does import random ans =

Checkpoint 9 b: 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 9 c: Explain in English what this code does import random while True:

Checkpoint 9 c: 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 52 executed

Note: Else Clauses on Loops Loop statements may have an else clause 52 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.

Other loop patterns: Read in text book. Post test loop while True: …. exit

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? Average 4. py 53

Other loop patterns: Read in text book. Loop and a half while True: ….

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: Average 5. py 54

Kiddy. Maths 4. py import random def test(num_questions): num_correct=0 for i in range(num_questions): a

Kiddy. Maths 4. 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: 55 print("correct!") num_correct+=1 else: print("Wrong! Correct answer is: ", ans) else: print(num_correct, "/", num_que stions) if __name__ == '__main__': test(5)

Post-test loop import random txt=" {0} x {1} = " a = random. randint(1,

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)

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