1 / 57

CSC1015F – Loop Structures

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

gamba
Download Presentation

CSC1015F – Loop Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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 thebodyof the loop • Each repetition of the loop body is called an iterationof the loop

  3. 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

  4. 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)

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

  6. 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)

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

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

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

  10. 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

  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)

  12. 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

  13. 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)

  14. 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.

  15. 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

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

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

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

  19. 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,'*')

  20. 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”

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

  22. More from the textbookAccumulating 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 reachedupdate the value of accumulator variable Python Programming, 2/e

  24. 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

  25. 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)

  26. 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)

  27. 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

  28. Indefinite or conditional loop • Computer stops the loop when a condition is no longer true • Event-controlled loop statements in Python: while • 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 Loops • Two kinds of loops

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

  30. 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

  31. 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

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

  33. 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?

  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

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

  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

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

  38. Data values Sentinel 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

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

  40. 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

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

  42. 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

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

  44. 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()

  45. 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 Checkpoint9.py

  46. 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.

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

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

  49. 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()

  50. 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!")

More Related